Sunday, September 12, 2010

Static Constructors in C#

Hi,
My first blog is about Constructors especially Static Constructors.

In C# Constructor can be classified in two type:
Role of constructors in OOP is very much visible & clear but sometimes clouds of doubts appear when static constructors are talked about.

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.
If above two points are confusing, have a look at following code and try to guess the result.

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:
  1. When dObj1 is created, Control goes to Derived class instance c'tor.
  2. Static c'tor for Derived class is called (as it is first use of class).
  3. Control goes to BaseClass instance c'tor. (as usual Base class is created before derived class)
  4. As step 3 is First use of Base class, it's static c'tor is called
  5. Base Class instance c'tor completes.
  6. Derived class instance c'tor completes.
  7. When dObj2 is created, Control goes to Derived class instance c'tor.
  8. Control goes to BaseClass instance c'tor.
  9. Step 5 and 6 are repeated.
I hope the explanation helps and does not create darker clouds. :-)

Wish you Good luck.

No comments:

Post a Comment