Static Constructor in c#


A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only so in C# there are two types of the constructor.

1.     Class constructor (static constructor).

2.     Instance constructor (non-static constructor).


A static constructor is used to initializing static data members as soon as the class is referenced the first time, whereas an instance constructor is used to create an instance of that class with <new> keyword.

Example of Static constructor:-

using System;
namespace StaticConstructorExampleNameSpace
{
    class StaticConstructorExampleClass
    {
        private static int Value;
        //Static constructor, value of data member id is set conditionally here.
        //This type of initialization is not possible at the time of declaration.
        static StaticConstructorExampleClass()
        {
            if (StaticConstructorExampleClass.Value < 10)
            {
                Value = 30;
            }
            else
            {
                Value = 200;
            }
            Console.WriteLine("Static<Class> Constructor for Class StaticConstructorExampleClass Called..");
        }
        public static void StaticMethod_PrintVlaue()
        {
            Console.WriteLine("StaticConstructorExampleClass.id = " + Value);
        }


        static void Main(string[] args)
        {
            //Print the value
            StaticConstructorExampleClass.StaticMethod_PrintVlaue();
            Console.ReadLine();
        }
    }
}


Note:-

1.      A static constructor does not take access modifiers or have parameters.

2.      A static constructor cannot be called directly.

3.      The user has no control over when the static constructor is executed in the program.

4.     A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

5.   A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.