Read Only Fields in C#

Read-only fields allow you to establish a point of data, whose value is not known at compile time, but that should never change once established. A read-only field cannot be changed after the initial assignment.

A readonly field can be given a value only by using an initializer when it is declared, or by assigning it a value within a constructor.

A readonly field can be initialized both at compile time and at runtime.
  • Compile time initialization: Unlike a constant field, a readonly field in not implicitly static.
    A readonly field can be initialized at class level at the time of its declaration only if it is static and the value is known at compile time.
    Ex:
    class MyMathClass
    {
    public static readonly double PI = 3.14;
    }
  • Runtime initialization: An instance (non-static) readonly field can only be initialized at runtime. This can be done only within the scope of an instance constructor and nowhere else.
    Ex:
    class MyMathClass
    {
    public readonly double PI;
    public MyMathClass ()
    {
    PI = 3.14;
    }
    }
    If the value of a static read-only field is not known until runtime, you must make use of a static constructor.
    Ex:
    class MyMathClass
    {
    public static readonly double PI;
    static MyMathClass()
    { PI = 3.14; }
    }
Static readonly fields should be initialized in a static constructor while instance readonly fields should be initialized in instance constructor(s).

A readonly field can be static or nonstatic. Unlike const, read-only fields are not implicitly static.

A const field gets determined at compile time, while a readonly field can be determined at runtime.

Related Post: The const keyword

No comments:

Post a Comment