Saturday, January 5, 2013

Difference between Constructor and Destructor in c#?


Constructor

A constructor is a special method which is called when a new object of a class is created. It is generally used to initialize the data.

Characteristic


  • Constructor does not have return type. 
  • Constructor can be parameterized.
  • Always Constructor name will be the same class name.
  • Constructor can be private and static.


Private Constructor

Private Constructor is used to restrict the user to cerate an abject outside the class i.e. No one can create the object of the class which contains private constructor. It is mostly used to make a Singleton class.

Example

public class LoanData
{
    // Private Constructor
    private LoanData()
    {
    }

    public static LoanData GetLoanData
    {
        get
        {
            object objData = HttpContext.Current.Session["LoanData"];
            if (objData == null || !(objData is LoanData))
            {
                //singleton object of LoanData
                objData = new LoanData();
                HttpContext.Current.Session["LoanData"] = objData;
            }

            LoanData loanData = objData as LoanData;
            return loanData;
        }
    }
}

Static Constructor

A static constructor is automatically called when first instance of the class is created. For second or more instances, it is not called.

Characteristics:


  • Access modifiers are not allowed on static constructor.
  • A static constructor can not be called directly
  • A static constructor initialized only static fields, it doesn’t initialize non-static fields.


Example

    public class Employee
    {
        private string _name;
        private string _sal;
        static string _department;

        //Static constructor
        static Employee()
        {
            _department = "Software";
        }

        // Copy constructor.
        public Employee(Employee employeeObj)
        {
            _name = employeeObj._name;
            _sal = employeeObj._sal;
        }

        // constructor.
        public Employee()
        {
        }

        // Parameterize constructor.
        public Employee(string name, int sal)
        {
            this._name = name;
            this._sal = sal;
        }

}


Destructor

Destructor is just opposite the constructor. It is just a method with ~(Tilde) character and called when garbage collector reclaim the memory.

Characteristics:


  • A destructor name is the same as class name.
  • A destructor is declared with the tilde (~) character.
  • Only one destructor is allowed in one class.
  • Destructor can not be parameterized.
  • Destructor does not return any value.


Example


    public class Employee
    {
        private string _name;
        private int _sal;

        // constructor.
        public Employee()
        {
        }

        // Destructor.
        ~Employee()
        {
        }
}

No comments:

Post a Comment