Static Constructor
In this lesson we will learn key facts about static constructor.
"Static constructor is used to initialize static data members when class is referenced for the first time means static constructor will not call from the second object creation on the class."
Example on how to create static constructor and when it calls during program execution.
public class Program
{
// Static Constructor
static int art = 10;
static Program()
{
Console.WriteLine("I am from Static Constructor");
}
// Default Constructor
public Program()
{
Console.WriteLine("I am from Default Constructor");
}
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for first instance
Program obj1 = new Program();
// Only Default constructor will invoke
Program obj2 = new Program();
Console.WriteLine("\nPress Enter to Exit.");
Console.ReadLine();
Console.Read();
}
}
Why we cannot overload the static constructor ?
public class Program
{
// Static Constructor
static int art = 10;
static Program()
{
Console.WriteLine("I am from Static Constructor");
}
// Default Constructor
public Program()
{
Console.WriteLine("I am from Default Constructor");
}
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for first instance
Program obj1 = new Program();
// Only Default constructor will invoke
Program obj2 = new Program();
Console.WriteLine("\nPress Enter to Exit.");
Console.ReadLine();
Console.Read();
}
}
You have given good clarity about static construtor. I wish you to put more useful .
ReplyDelete