find and solve || findandsolve.com
Please wait.....

Static constructor in C# example

In the C#, Static constructor is used to initialize static data members as soon as the class is referenced the first time, whereas an instance constructor.

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

   using System;  
   public class EmployeeInfo
    {
        public int Id;
        public String Name;
        public static float rateOfInterest;
        public EmployeeInfo(int id, string name)         {
            this.Id = id;
            this.Name = name;
        }
        static EmployeeInfo()
        {
            rateOfInterest = 9.5f;
        }
        public void display()
        {
            Console.WriteLine(Id + " " + Name+" "+rateOfInterest);
        }
   }
   public class AnotherClassEmployeeInfo{
       public static void Main(string[] args)
        {
            EmployeeInfo obj = new EmployeeInfo(1001, "Sylvia");
            EmployeeInfo obj1 = new EmployeeInfo(1002, "Rahul");             obj.display();
            obj1.display();
        }
    } 

Output

1001 Sylvia 9.5

1002 Rahul 9.5