ReadOnly Modifier And Static Constructor Concept In C#

First of all, try to understand the purpose of introducing readonly modifier in C# and .NET. Remember a few important points which are mentioned below are related to readonly modifier.

  1. With the help of readonly modifier, we can initialize the constant members during runtime.
  2. Constant members are implicitly static but we can declare readonly modifier as a static or non-static members as well. This would be an added advantage over the constant members.
  3. Using readonly modifier, we can assign the value to the constant members at the run time. 
    Here, it should be in a constructor method and remember once assigned value to readonly modifier, it cannot be changed later on.
  4. Readonly modifier can be used on the static or non static members
  5. Readonly modifier is not implicitly static like const members.

Now, let us see about the static constructor,

Remember important points, which are mentioned below related to static constructor.

  1. Static constructor is mainly used to initialize the static data members in the class.
  2. It is always getting invoked first other than any constructors declared in the class.
  3. It doesn’t have any access modifiers.
  4. There is only one static constructor per class.

Now, we will go through the code snippet given below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ReadonlyModifierCSharpCODE  
  8. {  
  9.     class A  
  10.     {  
  11.         public readonly int m;  
  12.         public static readonly int n;  
  13.         public A(int x)  
  14.         {  
  15.             m = x;  
  16.             Console.WriteLine("" + m);  
  17.         }  
  18.         static A()  
  19.         {  
  20.             n = 100;  
  21.             Console.WriteLine("" + n);  
  22.         }  
  23.     }  
  24.   
  25.     class Program  
  26.     {  
  27.         static void Main(string[] args)  
  28.         {  
  29.             A a = new A(10);  
  30.             Console.Read();  
  31.   
  32.         }  
  33.     }  
  34. }  
Output of the program given above is

100
10

Code Explanation=>

As mentioned above, static constructor is always  invoked beforeany constructors, which are declared in the class.

Here, first of all it prints 100.

At this moment, static data member n is initialized in static constructor.

In the code given above, I have used static or non-static readonly modifiers n and m respectively.

Now, after invoking static constructor, it invokes non-static constructor and prints =>10

Readonly modifiers are initialized or are assigned values to them in constructor methods only.

In the program given above, there is only one static constructor.