readonly


A readonly field of a class may be created using the readonly keyword. A readonly field can only be given a value through:

  1. an initializer when it is declared or
  2. assigning it a value in a static constructor.

Readonly fields can be used to create constants. Below is an example of a readonly field.

// ReadOnly - Using the readonly modifier

using System;

class X
{
    public static readonly int Size = 10;
}


class Program
{
    static void Main()
    {
        int[] array = new int[X.Size];

        // X.Size = 100;
    }
}

The static field Size of class X is declared as readonly. It serves as the dimensions of an array when used in Main(). The commented code does not work because Size has been declared readonly. If it is uncommented, a compile error results.