This is a mirror of official site: http://jasper-net.blogspot.com/

C#-Constructors,Static Constructors and Destructors Execution in Inheritance

| Sunday, March 21, 2010
While taking interview for .NET Technologies i often ask about the execution sequence of the constructor and destructor in inheritance But from the my experience i have found that lots of people are still confused with execution sequence of constructor and destructors. Lets create a simple example and learn some basic things that is very important while using inheritance in C#.

   * Constructors will be executed in from parent to child sequence means first parent class constructor will be executed then after that child class constructor will be executed.
   * Destructors execution order is reverse then constructors first it will execute child class destructor and then it will execute the parent class destructor.
   * Static constructors are different then the normal constructors and its executes when first object of class is created it will be executed. Most of people are very confused this kind of scenario in inheritance. Here scenario will be like when the first object of child class created then it will execute the child class static constructor and then after the parent class static constructor is executed. After that it will never got executed.

Lets create a simple class which will illustrate the above worlds. First lets create a class A with constructor,destructor and a static constructor.

public class A  
{  
static A()  
{  
System.Console.WriteLine("A Static Constructor");  
}

public A()  
{  

System.Console.WriteLine("A public constructor");  
}  

~A()  
{  

System.Console.WriteLine("A Destructor");  
}  
}  

Read more: DotnetJaps

Posted via email from jasper22's posterous

0 comments: