Constructor and Destructors in C#.Net

This C#.Net tutorial explains, what are constructor and destructors in C#.Net with examples.

Constructor in C#.net

A constructor is a 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.

Constructor has the same name as the name of the class in C#.Net.

The 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 in c#.net

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 in c#.net

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()
{

}

You may like following c sharp tutorials:

You may like following C#.Net tutorials:

Hope this C sharp tutorial explains what are constructors in c#.net and what are Destructors in c#.net.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>