Static constructor in C#
To initialize the class before the first instance is created, a static constructor is called automatically. A static constructor is not called directly and does not take parameters. A static constructor is executed in the program automatically and a user has no control on it. Static constructor initializes static data members when the class is referenced first time. The difference between an instance constructor and a static constructor is, an instance constructor is used to initialize data whereas a static constructor is used to initialize only static members.
In c#, we declare a static constructor using a ‘static ‘ keyword. In the code given below, we have declared static variable ‘i’. In the static constructor, we have initialized static variable ‘i’ to zero.
public class ItemClass
{ private string ItemCode;
private string ItemName;
private string ItemDescription;
private string ItemCategory;
private double ItemPrice;
private string ItemUnit;
static int i;
public ItemClass()
{ i=i+1;
ItemCode = “Ioo1”;
ItemName = “Reading Guage”;
ItemDescription = “Trading”;
ItemCategory = “Instruments”;
ItemPrice = 10;
ItemUnit = “Kgs”;
MessageBox.Show(“The number of instances are:”+i);
}
static ItemClass()
{
i = 0;
}
}
Object Oriented Programming Articles