C Sharp static constructor

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# static constructor

C# static constructor is used to initialize static fields. It can also be used to perform any action that is to be performed only once. It is invoked automatically before first instance is created or any static member is referenced.

Points to remember for C# Static Constructor

  • C# static constructor cannot have any modifier or parameter.
  • C# static constructor is invoked implicitly. It can't be called explicitly.

C# Static Constructor example

Let's see the example of static constructor which initializes the static field rateOfInterest in Account class.

  1. using System;  
  2.    public class Account  
  3.     {  
  4.         public int id;   
  5.         public String name;  
  6.         public static float rateOfInterest;  
  7.         public Account(int id, String name)  
  8.         {  
  9.             this.id = id;  
  10.             this.name = name;  
  11.         }  
  12.         static Account()  
  13.         {  
  14.             rateOfInterest = 9.5f;  
  15.         }  
  16.         public void display()  
  17.         {  
  18.             Console.WriteLine(id + " " + name+" "+rateOfInterest);  
  19.         }  
  20.    }  
  21.    class TestEmployee{  
  22.        public static void Main(string[] args)  
  23.         {  
  24.             Account a1 = new Account(101, "Sonoo");  
  25.             Account a2 = new Account(102, "Mahesh");  
  26.             a1.display();  
  27.             a2.display();  
  28.   
  29.         }  
  30.     }  

 

Output:

101 Sonoo 9.5
102 Mahesh 9.5