Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Constructor And Destructor in C# (http://www.go4expert.com/articles/constructor-destructor-c-sharp-t15638/)

sanjitsil 27Dec2008 17:31

Constructor And Destructor in C#
 

Introduction



Before designing a class, we should have a very clear understanding about constructor. In this article I will discuss definition, types and features of constructor.

Definition
A constructor looks like a special method having no return type and its name is same with the class name. If we do not declare constructor explicitly for a class, compiler will create a default constructor at run time.
Access Modifiers
Access modifiers of constructor can be public, private, protected, internal and extern. A public constructor is called when the class is instantiated. A private constructor prevents the creation of the object of the class. It is used in classes having only static members. A class having internal constructor cannot be instantiated outside of the assembly. A protected constructor of base class can only be called from the derived class within derived class constructor. When a constructor having an extern modifier, the constructor is said to be an external constructor, because the same does not provide any actual implementation. Remember that a private constructor can be accessed by a public constructor of the same class through constructor chaining.

Types of Constructor



Constructor is of two types: Static Constructor and Instance Constructor

Static Constructor

Static constructors are called before the first instance of the class is created or any static members are accessed or used whichever is earlier. Followings are the features of static constructor:
  • A Static constructor cannot be overloaded.
  • There is no access modifier in Static constructor and they don't take any arguments also.
  • The static constructor for a class executes only once throughout the life time of the program.(see Code Listing I)

    Code Listing I:
    Code: CSharp

    class Parent
        {
            public Parent()
            {
                Console.WriteLine("Instance Constructor called");
            }

            static Parent()
            {
                Console.WriteLine("Static Constructor called");
            }
        }
       
        class Program
        {
            static void Main(string[] args)
            {
                Parent p = new Parent();
                Parent p1 = new Parent();
                Parent p2 = new Parent();
            }
        }

  • Static constructor does not support Constructor Channing.
  • Static constructor can call only static members.
  • Static constructor is getting called before instance constructor (see Code Listing II)
    Code Listing II:
    Code: C#

    class Parent
        {
            public Parent()
            {
                Console.WriteLine("Parent Default Constructor");
            }

            public Parent(int x)
            {
                Console.WriteLine("Parent Constructor With Single Parameter");
            }
            static Parent()
            {
                Console.WriteLine("Static Constructor");
            }
        }

        class Child : Parent
        {
            public Child():base(10)
            {
                Console.WriteLine("Child Constructor");
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Child child = new Child();
               
            }
        }

Instance Constructor

Instance constructor is used to create and initialize instance and it is invoked when we create a new object of the class.

Features of Constructor



Constructor having different features as follows:

Constructor can not be virtual. When constructor is invoked the virtual table would not be available in the memory
  • Constructor Chaining

    Constructor chaining means call one constructor from another constructor. In order to call one constructor from another, we use base (parameters) or: this (parameters)

    We use base (parameters) to call a constructor in the base class and we use this (parameters) to call a constructor in the current class. (see Code Listing II)


  • Inheritance

    A constructor of a base class can not be inherited to its derived class. But base class constructor or parent class constructor can be invoked from derived class or child class. (see Code Listing III)

    Code Listing III:
    Code: C#

    class Parent
        {
            public Parent()
            {
                Console.WriteLine("Parent Default Constructor");
            }

            public Parent(int x)
            {
                Console.WriteLine("Parent Constructor With Single Parameter");
            }
        }

        class Child : Parent
        {
            public Child():base(10)
            {
                Console.WriteLine("Child Constructor");
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Child child = new Child();
            }
        }

  • Overloading

    Constructor can be overloaded. In the following code snippet, there are four overloaded constructor:

    Code Listing IV:
    Code: C#

    public Sample()//Default constructor without parameter.
     {
     
     }
     public Sample(int iVal) //Constructor with one parameter.
     {
     
     }

     public Sample(int iVal, string strVal) //Constructor with two     
                                              parameters.
      {
     
     }
     public Sample(string strVal,int iVal)//Constructor  with two   
                                            parameters in different order.
     {
     }

Destructor



Destructors are used to destruct instances of classes. Following are features of destructor:
  • A class can have one destructor only.
  • Destructors cannot be inherited or overloaded.
  • Destructors are invoked automatically.
  • Destructor can not have modifiers or parameters.
When destructor is called, Finalize is called from destructor implicitly. When derived class destructor is called, the base class destructor is also getting called.

Code Listing V:
Code: C#

class Parent
{
    ~ Parent()  // destructor
    {
        //Code for cleanup resources
    }
}

Execution Order



Base constructor is getting called first. In general, destructors are called in the reverse order of the constructor calls.

For example, if class A is the base class and class B inherit class A and class C inherit class B. Constructor will be fired for class A first, class B second and at last for class C.

But destructor will be fired in reverse order: class C first, class B second and at last for class A.

Conclusion



Proper understanding of constructor makes the class design easier and it is advisable to use default constructor and not to use empty destructor. It should be noted that in .net CLR takes care for garbage collection automatically.

shabbir 6Jan2009 12:24

Re: Constructor And Destructor in C#
 
Nomination for article of the month for December 2008 Started.


All times are GMT +5.5. The time now is 23:27.