Readonly and readonly attributes
The readonly keyword is used to modify a field. When a field is declared as readonly, it can only be assigned to it during declaration in the corresponding class and in the constructor.
- Declare Initialization
public readonly int y = 5;
- For instance fields, they are initialized in the instance constructor of the class containing fields; for static fields, they are initialized in the corresponding static constructor.
class Age { readonly int _year; Age(int year) { _year = year; } void ChangeYear() { //_year = 1967; // Compile error if uncommented. } }
The field _ year is declared as readonly, so it is assigned a value in the constructor and cannot be changed in the method ChangeYear.
Difference between readonly and const
The const field can only be initialized during declaration, while the readonly field can be initialized during Declaration and the constructor. Therefore, the readonly field may have different values depending on the constructor. In addition, the const is the compile time, And the readonly field can be used for the run time, as shown below:
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
Example
public class ReadOnlyTest { class SampleClass { public int x; // Initialize a readonly field public readonly int y = 25; public readonly int z; public SampleClass() { // Initialize a readonly instance field z = 24; } public SampleClass(int p1, int p2, int p3) { x = p1; y = p2; z = p3; } } static void Main() { SampleClass p1 = new SampleClass(11, 21, 32); // OK Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z); SampleClass p2 = new SampleClass(); p2.x = 55; // OK Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z); } } /* Output: p1: x=11, y=21, z=32 p2: x=55, y=25, z=24 */
We can see that the value of readonly is different when different constructors are called.
In the preceding example, use the following statement:
P2.y = 66; // Error
The compiler error message will be received:
The left-hand side of an assignment must be an l-value
This is the same as an error that is returned when you try to assign a value to a constant.