Hi readers, In this tutorial, I am going to explain you static constructor in C#.  A static constructor is a special type of constructor which is used to initialize the static data members of the class.

What is a static constructor in C#?

A static constructor is a special type of constructor which is used to initialize the static data members of the class. It is invoked automatically before the first instance is created or any static member is referenced. A static constructor is created with no access modifiers and with no parameters. It cannot access any non-static member of the class.

The syntax for creating a static constructor:

Suppose if I have a class called MyClass then the static constructor of the class is created as follows:

class MyClass
{
static MyClass
{
//constructor invoked
}
}

Example:

using System;

public class Student
{
public static int _iRollNo;
public static String _sName;

static Student()
{
_iRollNo = 1;
_sName = "Vinod";
 
}
public static void DisplayRecord()
{
Console.WriteLine("Roll No " + " " + _iRollNo + ". Name " + _sName);
}
} 
class Program
{
static void Main(string[] args)
{

Student.DisplayRecord();
Console.ReadLine();
 
}
 
}

Output:

Roll No  1. Name Vinod

Interesting point for the static constructor:

  • A static constructor is called automatically when the class is loaded and before the instance constructor.
  • A static constructor can not have access modifier and cannot be called by your program (It is invoked automatically).

View More:

Conclusion:

I hope you would love this post. Please don’t hesitate to comment for any technical help. Your feedback and suggestions are welcome.

Thank You.

Leave a Comment