Readonly Field


Readonly field is used to define a constant that might change.

  • In C#, readonly keyword is used to declare fields as read only.
  • The values for readonly fields can be initialized either at the time of declaration or inside a constructor of the same class.
Example - Initialized in the declaration
public readonly int y = 1;
Example - Constructor
public class Sample
{
    readonly int _x;
    public Sample(int x)
    {
        _x = x;
    }
    void ChangeValue()
    {
        //_x = 6; // This will generate a compile error.
    }
}

Back to Notes