C# knowledge series: the difference between readonly and const

reference:

         https://www.cnblogs.com/daidaibao/p/4214268.html

         https://www.cnblogs.com/tinya/p/4560864.html

         https://www.jb51.net/article/41796.htm

 

to sum up:

  • The const field can only be initialized in the declaration of the field.

         The readonly field can be initialized in the declaration or constructor. Therefore, depending on the constructor used, the readonly field may have different values.

  • The const field is a compile-time constant, and the readonly field can be used as a runtime constant.
  • const is static by default, and readonly must be declared explicitly if it is set to static.
  • const For reference type constants, the only possible values ​​are string and null; readonly can be any type

Guess you like

Origin blog.csdn.net/qq1090504117/article/details/111580904