Constructor And Destructor in C#

Discussion in 'C#' started by sanjitsil, Dec 27, 2008.

  1. sanjitsil

    sanjitsil New Member

    Joined:
    Dec 9, 2008
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Lead Software Engineer in an MNC
    Location:
    Hyderabad

    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:
      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:
          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:
          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:
      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:
    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.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice