C# Static class and constructor: constructor in static classes in c#

Static classes in C# doesn’t have instance constructor(constructor used to initialized instance of a class) since it can’t be initialized. Static class is initialized only once when they are used first time in application.

So i was wondering how we can initialize a member if really we need. The answer is using static constructors.

Here is the example of how you can use static constructors in your static class:

static class StaticClass
{
static StaticClass()
{
System.Windows.Forms.MessageBox.Show(“I m crated”);
}
public static String Hi()
{
return “hi”;
}
}

Here, messagebox will be shown when first time StaticClass.Hi() method will be called.

Note: static constructors could be used in normal classes also.