What is an Instance constructor?

Instance Constructor is a speical type of  method in a class which have the same name as a class that gets executed when a new instance (object) of a class is creaetd.

Student s = new Student();

In the above line, C# compiler actually calls the constructor of Student class to create an instance.  The constructor allocates the required memory and returns the reference of the memory.

Strictly speaking constructors are not methods (you cannot invoke a constructor with a dot notation). Constructors are executed when the object is instantiated.  If there are no constructors specified in the class, then C# by definition automatically provides a parameterless constructor to the class which initializes the data members to zero-equivalent values.  There can be any number of constructors in a class (but the parameter list should vary).

Points to Remember when you are writing a constructor

  • Constructors dont have return type
  • Constructor name should be same as the class name
  • Constructor cannot be invoked by dot notation. 
  • A class with only private constructors cannot be instantiated

There is something called as "Class Constructor" (also known as static constructors)  in .NET. We will discuss this in a seperate post.

A good article on Constructor can be found at Constructors

Advertisements

Author: azagappan

Hi.. I am Azagu. I live in Chennai, Tamil Nadu, India. I am a .NET developer. You can reach me at azagappan at gmail.com

2 thoughts on “What is an Instance constructor?”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s