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.

Explore post tags

4 Comments

  • İncelediğiniz paketteki hesaplar yerli-yabancı karışık data hesaplardır. Eğer ihtiyacınız türk takipçi paketleriyse İnstagram Türk Çekiliş Takipçi paketlerimizi inceleyebilirsiniz.

  • Definitely imagine that that you said. Your favourite reason seemed to be at the web the easiest factor to keep in mind of. I say to you, I definitely get annoyed at the same time as other folks consider concerns that they plainly do not recognize about. You controlled to hit the nail upon the highest and outlined out the whole thing with no need side-effects , other people can take a signal. Will probably be back to get more. Thank you

  • Hey! I’m at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!

  • Hello, i feel that i saw you visited my web site thus i got here to return the choose?.I am attempting to to find issues to enhance my site!I suppose its ok to make use of some of your ideas!!|