Powered by Blogger.

Sunday, February 23, 2014

Constructor and Destructors in C#.Net




In this post we will discuss about what are constructors in C#.Net.

Also check out:

- Retrieve browser details using C#.Net

- Get nth highest lowest salary in SQL Server 2008

- Triggers in sql server 2008

- A constructor is special a method that automatically runs when the class is first created. A constructor is a method in the class which gets executed when its object is created.

- It has the same name as the name of the class.

- Constructor doesn't define any return type, not even void.

- If you don’t create a constructor, .NET supplies a default public constructor that does nothing. If you create at least one constructor, .NET will not supply a default constructor.

- Constructors can be overloaded.

public class Employee
{
    public Employee()
    {
        // This is the constructor.
    }
}

Constructors can be overloaded like below:

public class Employee
{
    public Employee()
    {
        // This is the constructor.
    }

  public Employee(int EmployeeID)
    {
        // This is the overloaded constructor.
    }
}

Below is the way to call constructor like below:

Employee objEmployee = new Employee()
Employee objEmployee1 = new Employee(5); //will execute the overloaded constructor.

- We can also declare a constructor as private. In that case we can not create object of the class.

Static constructor:

- We can also declare a constructor as static. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation.

- But there can be only one static constructor in the class.

- The static constructor should be without parameters.

- It can only access the static members of the class.

- There should be no access modifier in static constructor definition.

Destructors:
- A destructor is a method called once an object is disposed and can be used to cleanup resources used by the object.

- Once the object is collected by the garbage collector, this method is called.

Example:
~Employee()
{

}



0 comments

Post a Comment