Home >Backend Development >C++ >What's the Difference Between `const` and `readonly` in C#?
The differences between the const and readonly in C#
and
are two keywords in C#. They play different roles in defining constant and only reading fields.
const
readonly
and
const
readonly
Value:
const
The field is hidden as a static field, and the readonly
field can be an instance field or a static field. const
, and the readonly
field uses field reference access. const
ClassName.ConstantName
Considering the following C# code: readonly
cannot be changed after the statement, and can be assigned any other part of the class before the constructor or the constructor exits.
When to use Const or readonly:
<code class="language-csharp">public class ConstReadonlyExample { public const int CONST_VALUE = 2; // 常量值必须立即赋值 public readonly int RO_VALUE; // 只读值可以在运行时赋值 }</code>
When the value is known and does not change it during the program execution, CONST_VALUE
is used. RO_VALUE
can be used when it is at a certain time point.
The above is the detailed content of What's the Difference Between `const` and `readonly` in C#?. For more information, please follow other related articles on the PHP Chinese website!