Static Constructor in C#


Static Constructors:


It is a Special type of constructor. It gets called before the creation of first object of class(Probably at the time of loading an assembly).


Rules to create a static constructor:

  • There is no access modifier require to define a static constructor.
  • There may be only one static constructor in a class.
  • The static constructor may not have any parameters.
  • This constructor may only access the static members of the class

Static constructor is used to initialize static data members as soon as the class is referenced first time.You can also initialize static data members where we declare them in the code.

Like this :
public static int id = 10;

But value of one static member may depend upon the value of another static member .In order to handle such cases you need some manipulation before static members going to be initialize.
This you can achieve through static constructors.


namespace StaticConstructor
{


class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Id value is " + ClsStaticConstructor.id);
}
}


class
ClsStaticConstructor
{
public static int id;

static ClsStaticConstructor()
{
if (Sample.Value == 10)
id = 20;
else
id = 40;
}
}


public class
Sample
{
public static int Value = 10;
}


}


Output
:

Id value is : 20


No comments: