My first blog is about Constructors especially Static Constructors.
In C# Constructor can be classified in two type:
- Instance Constructor. (or Constructor, I'll use this term from now on.)
- Static Constructor.
Let me first define constructor: A constructor is a member of its Class which is invoked when object of a class is created. It is invoked when new operator is used (see Reflection also but I'm not covering it here). and it's purpose is to initialize the instance variables.
Similarly Static Constructors can be defined as a member of its Class which is used to initialize the static variables and it is invoked
- Only once during life time of class.
- At the point when class is first used.
class BaseClass
{
static BaseClass()
{
Console.WriteLine("BASE : static c'tor");
}
public BaseClass()
{
Console.WriteLine("BASE : instance c'tor");
}
}
class DerivedClass : BaseClass
{
static DerivedClass()
{
Console.WriteLine("DERIVED : static c'tor");
}
public DerivedClass()
{
Console.WriteLine("DERIVED : instance c'tor");
}
}
class Program
{
public static void Main(string[] args)
{
DerivedClass dObj1 = new DerivedClass();
DerivedClass dObj2 = new DerivedClass();
}
}
Output:
DERIVED : static c'tor
BASE : static c'tor
BASE : instance c'tor 10
DERIVED : instance c'tor
BASE : instance c'tor 10
DERIVED : instance c'tor
Explanation:
- When dObj1 is created, Control goes to Derived class instance c'tor.
- Static c'tor for Derived class is called (as it is first use of class).
- Control goes to BaseClass instance c'tor. (as usual Base class is created before derived class)
- As step 3 is First use of Base class, it's static c'tor is called
- Base Class instance c'tor completes.
- Derived class instance c'tor completes.
- When dObj2 is created, Control goes to Derived class instance c'tor.
- Control goes to BaseClass instance c'tor.
- Step 5 and 6 are repeated.
Wish you Good luck.
No comments:
Post a Comment