C Sharp static constructor

C# static constructor

To initialize the static fields and to perform an action to be performed only once, the C# static constructor is used. Before the first instance is created or any static members are referenced, the static constructor is invoked implicitly and automatically. It can’t have any modifier or parameter and can’t be called explicitly.

Example:

using System;  
   public class Loan  
    {  
        public int id;   
        public String type;  
        public static float rateOfInterest;  
        public Loan(int id, String type)  
        {  
            this.id = id;  
            this.type = type;  
        }  
        static Loan()  
        {  
            rateOfInterest = 3.2f;  
        }  
        public void display()  
        {  
            Console.WriteLine(id + " " + type + " "+rateOfInterest);  
        }  
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Loan b1 = new Loan(10, "Vishal Gupta");  
            Loan b2 = new Loan(11, "Thomas Edison");  
            b1.display();  
            b2.display();  
 
        }  
    }

Output:

Explanation:

In the above example, we are using the static constructor to initialize the static field rateOfInterest in the Loan class.

Please Share