Different Types of Constructors in C#

A constructor is a method in the class which gets executed when its object is created.

A constructor is usually used to initialize data members of the class.

There are four different types of constructors:

  1. Default Constructor

When you do not declare any constructor, the class will call its default constructor. The default constructor is a parameter less constructor which will be called by a class object.

public class myClass
{
   private string myString;
   private int myInt;

   public myClass()
   {
     myString = "some string";
     myInt = 12;
   }
}

The default constructor will be executed whenever the class is initialized.

myClass objmyClass = new myClass();
  1. Parameterized Constructor

Called also constructor overloading, that means, we can have constructors with different sets of parameters.

public class myClass
{
   private string myString;
   private int myInt;

   public myClass()
   {
     myString = "some string";
     myInt = 12;
   }
   public myClass(string mString, int mInt)
   {
     myString = mString;
     myInt = mInt;
   }
}

o invoke the parameterized constructor, use this:

myClass objmyClass = new myClass("some string",12);
  1. Copy Constructor

Copy constructor is the parameterized constructor which takes a parameter of the same type. It allows you to initialize a new object with the existing object values.

public class myClass
{
   private string myString;
   private int myInt;

   public myClass()
   {
     myString = "some string";
     myInt = 12;
   }
   public myClass(string mString, int mInt)
   {
     myString = mString;
     myInt = mInt;
   } 

   public myClass(myClass mClass)
   {
     myString = mClass.myString;
     myInt = mClass.myInt;
   }
}

Here’s an example:

myClass objmyClass1 = new myClass("some string",12);
myClass objmyClass2 = new myClass(objmyClass1);
  1. Static Constructor

This is a new concept introduced in C#. This is a special constructor and gets called before the first object is created of the class. Static constructor is only called once while creation of the first instance of the class.

public class myClass
{
   static myClass()
   {

   }
}

Notes for Static Constructors:

  1. There can be only one static constructor in the class.
  2. The static constructor should be without parameters.
  3. It can only access the static members of the class.
  4. There should be no access modifier in static constructor definition.
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s