readonly keyword can be used in the following three cases
1. In the field declaration, readonly indicated only during the field or assignment statement in the same class constructor. It can be allocated and reallocated several times in a read-only field field declarations and constructor.
After the constructor exits, you can not be assigned readonly field.
Value Type: since the value of the direct type contain data, the field value belonging readonly type immutable.
Reference types: As a reference type that contains references to their data, and thus belong to a field readonly reference type must always refer to the same object. This object is immutable. readonly modifier prevented instance reference field replaced with another type. However, the modifier does not prevent a read only modify the field by the data field instance.
2. Readonly struct definition, readonly indicating struct is immutable.
3. The method returns ref readonly, readonly modifier indicates that the method returns a reference, and not allowed to write to a reference.
readonly
Keyword is different from the const keyword. const
Field can only be initialized in the declaration of the field. It can be assigned several times in the field and declare any constructor readonly
field. Thus, according to the constructor is used, readonly
the fields may have different values. Further, although the const
field is a compile-time constant, the readonly
field can be used to run constants