An Introduction to the C# Readonly Property
What Is Readonly in C#?
The readonly keyword in C# is an access modifier that prevents a field from being modified after the object containing the field has been constructed. As such, it works to ensure that the value of the field does not change during runtime. In other words, a readonly field can be initialized only once in its declaration or in a constructor. After being initialized, the field cannot be changed.
When to Use Readonly in C#
Readonly is most often used for constants that store values that are known and fixed at compile time or during program initialization. Readonly, when used to initialize fields, allows the field to have different values in different instances of a class. This makes it useful when individual instances of a class may need different values, while all values must remain constant within an instance.
How to Declare Readonly in C#
A readonly field is declared with the readonly keyword. For example:
public readonly int x = 10;
It is also possible to assign a readonly field during initialization in a constructor:
public class MyClass
{
public readonly int x;
public MyClass()
{
x = 10;
}
}
In this case, the value of x can be set to any value within the constructor, but outside of the constructor, it is immutable.
Access Modifiers and Readonly
The same access modifiers that apply to other fields also apply to readonly fields. The access modifiers can determine whether other classes and methods can access and modify the readonly field.
Conclusion
The readonly keyword in C# is an access modifier that ensures that the value of a field does not change during runtime. It allows for different values in different instances of a class, while ensuring that all values remain constant within an instance. Readonly fields are declared with the readonly keyword and can be assigned a value during initialization in a constructor.