readonly Fields

The readonly  keyword is used for fields that will not allow modification of values. readonly  fields have similar characteristics as constants except that you can allow a readonly field to have no value from the declaration. Even though, you must assign values for readonly fields inside the class constructor. Once assigned a value, a readonly field’s value cannot be changed. Doing so will result into a compiler error.

namespace ReadOnlyFieldsDemo
{
    public class Sample
    {
        readonly int y = 10;
        readonly int x;
 
        public Sample(int number)
        {
            x = number;
        }
    }
}

Example 1 – readonly Fields Demo

The class above defined two readonly fields. The first one is initialized a value at the declaration. The other one was assigned a value in the class constructor.