C# Static Constructor

In C#, static constructor is the one which is used to initialize static fields. It can also be used to do the task which needs to be done once only. It is invoked automatically when a constructor is called or any static filed is referenced.

  1. We can't apply any modifier to static constructor.
  2. It can't be called explicitly.
Let's see an example of static constructor:
C# Static Constructor Example
using System;
public class Student
{
            int id;
            string name;
            static int batch;
            static string course;
            Student(int id,string name)
            {
                        this.id=id;
                        this.name=name;
            }
            static Student()
            {
                        batch=2017;
                        course="B. Tech.";
            }
            public void display()
            {
                        Console.WriteLine(id+" "+name+" "+course+" "+batch);
            }
            public static void Main(string[] args)
            {
                        Student s1=new Student(101,"Ayush Sharma");
                        Student s2=new Student(102,"Vimal Kumar");
                        s1.display();
                        s2.display();
            }
}
Output
101 Ayush Sharma B. Tech. 2017
102 Vimal Kumar B. Tech. 2017