C# Keywords Tutorial Part 68: readonly
In C#, the readonly
keyword is used to declare that a field or variable can only be assigned a value once, either at the time of declaration or in the constructor of the class where it’s defined. Once assigned, the value cannot be changed for the lifetime of the instance.
Here’s a brief explanation and example:
using System; public class MyClass { // Declaration with initialization public readonly int readOnlyField = 10; // Constructor public MyClass(int value) { // Assigning value to readonly field in the constructor readOnlyField = value; } public void ChangeValue(int newValue) { // Error: Cannot assign to 'readOnlyField' because it is read-only // readOnlyField = newValue; } } class Program { static void Main(string[] args) { MyClass myObj = new MyClass(20); Console.WriteLine(myObj.readOnlyField); // Output: 20 // Error: Cannot assign to 'readOnlyField' because it is read-only // myObj.readOnlyField = 30; } }
In this example:
readOnlyField
is declared asreadonly
, so it can be assigned a value either at the time of declaration or within the constructor.- Once assigned, its value cannot be modified.
- Any attempt to modify the value of
readOnlyField
outside of the constructor or without using the constructor will result in a compilation error.
The readonly
keyword is useful when you have fields whose values are supposed to be set once and remain constant throughout the lifetime of the object. It ensures the immutability of those fields, adding to the predictability and maintainability of your code.
Leave a Reply