The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. Compilers and verification ensure that readonly fields are not written to by any method other than a constructor. Note that reflection can be used to modify a readonly field.
In this example, the value of the field year cannot be changed in the method ChangeYear, even though it is assigned a value in the class constructor:
class Age
{
readonly int _year;
Age(int year)
{
_year = year;
}
void ChangeYear()
{
_year = 1967; // Will not compile.
}
}
You can assign a value to a readonly field only in the following contexts:
- When the variable is initialized in the declaration, for example:
public readonly int y = 5;
- For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:
public static readonly uint l1 = (uint)DateTime.Now.Ticks;
Also, in C#, there are some performance issues to consider when initializing fields by using inline syntax versus assignment syntax in a constructor.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5