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.
- With the help of readonly modifier, we can initialize the constant members during runtime.
- 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.
- 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. - Readonly modifier can be used on the static or non static members
- 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.
- Static constructor is mainly used to initialize the static data members in the class.
- It is always getting invoked first other than any constructors declared in the class.
- It doesn’t have any access modifiers.
- There is only one static constructor per class.
Now, we will go through the code snippet given below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ReadonlyModifierCSharpCODE
- {
- class A
- {
- public readonly int m;
- public static readonly int n;
- public A(int x)
- {
- m = x;
- Console.WriteLine("" + m);
- }
- static A()
- {
- n = 100;
- Console.WriteLine("" + n);
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- A a = new A(10);
- Console.Read();
-
- }
- }
- }
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.