Saturday, February 14, 2009

What are constructors in C# - A Step Ahead Series?

Introduction


In a simple words Constructor is nothing but a method, a special kind of method of a class, which gets executed when its (class) object is created.

Now, let’s take above in broader sense, A constructor is a class method automatically executed whenever class’s object is created or whenever class is initialized. Consider following bit of code:


public class MsDotNetHeaven
{
public MsDotNetHeaven()
{
//A default Constructor
}

//Class members

}


In above snippet, try to change the name of constructor from MsDotNetHeaven to MsDotNetMentor and see whats happen, you have to put same name as you gave it to class.

Behind the scenes:

What happened behind the scenes : whenever you try to create an object of class or initialize a class, then the default constructor is invoked.


//Initializes the Class
MsDotNetHeaven objMsDnH = new MsDotNetHeaven();


Types of Constructor


This is a n issue of debate but I always like to segregated Constructors in following types:


  1. Default Constructor

  2. A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.

  3. Parameterized Constructor

  4. Besides a default constructor when its need to pass some argument on the initialization of a class a parameterized constructor is come to picture. It follows the same rules as default constructor with a difference that it has some parameters which also differentiate it from default constructor. Go through following snippet:


    public class MsDotNetHeaven
    {
    public MsDotNetHeaven()
    {
    //A default Constructor
    }

    public MsDotNetHeaven(String strName)
    {
    //A parameterized Constructor having one parameter
    }

    public MsDotNetHeaven(String strFirstName, String strLastName)
    {
    //A parameterized Constructor having two parameters
    }


    //Class members

    }


    Note:
    1. A default constructor should be explicitly declared while declaring parameterized constructor.

    2. Some writer also take Private constructor and Static Constructor as types of constructor but in my view these are constructor with different modifiers so behave differ; I will cover these in next section.


Access Modifiers and Prefix with Constructors


By default Constructors are public but we can also use other modifiers and prefix like private and static. With the use of these modifiers constructors behave differently:

Using Access Modifier private with Constructor

When put private as access modifier to constructor then that constructor is known as private Constructor

A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.

Some time there is a need where we have not allow outer world to get instantiate our class then we need to use private modifier with constructor. Consider following piece of code:


public class MsDotNetHeaven
{
private MsDotNetHeaven()
{
//A default Constructor as private
}

//Class members

}


Now, whenever you try to invoke following piece of code:


//Initializes the Class
MsDotNetHeaven objMsDnH = new MsDotNetHeaven();


it throws an error: Constructors. MsDotNetHeaven. MsDotNetHeaven ()' is inaccessible due to its protection level

Now, question comes to mind if the above contains error then what the use is of private constructor, we can make above class to be initialized by declaring another public constructor, modify above code-snippet with bellow one:


public class MsDotNetHeaven
{
private MsDotNetHeaven()
{
//A default Constructor as private
}
public MsDotNetHeaven(String strName): this()
{
//A parameterized Constructor having one parameter
System.Console.WriteLine(“My name is : “ + strName);
}

//Class members
}


Now, you can initialize class as follow:


//Initializes the Class
MsDotNetHeaven objMsDnH = new MsDotNetHeaven(“Gaurav Arora”);


Using prefix static with Constructor

With the use of static with constructor gives a name as static constructor

For C++ developers it’s a new concept introduced in C#.

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Consider the following:


public class MsDotNetHeaven
{
static MsDotNetHeaven()
{
//A static Constructor
// Can only access static members here.

System.Console.WriteLine("I am a static constructor.");
}

//Class members

}


Now whenever you create an instance of the class MsDotNetHeaven the line I am a static constructor get printed.

Consider following piece of code:


public class MsDotNetHeaven
{
static MsDotNetHeaven()
{
//A static Constructor
// Can only access static members here.

System.Console.WriteLine("I am a static constructor.");
}

public MsDotNetHeaven()
{
//A default Constructor
}

//Class members

}


Above code is perfectly alright and will perform same result as earlier code.

Calling Parent Class Constructors in child class during inheritance


Now, suppose a scenario when you are inheriting a class and want to use Parent class constructor then how to attain that.

Simple the same has been achieved by using base()
Consider following code-snippet


public class MsDotNetHeaven
{
public MsDotNetHeaven()
{
//A default Constructor
}

public MsDotNetHeaven(String strName)
{
//A parameterized Constructor having one parameter
}

//Class members

}

public class MsDotNetMentor : MsDotNetHeaven
{
public MsDotNetMentor ()
{
//A default Constructor
}

public MsDotNetMentor (String strName) : base(strName)
{
//A parameterized Constructor having one parameter
}

//Class members

static void Main()
{
MsDotNetMentor objMsDnM = new MsDotNetMentor(); //(A)
MsDotNetMentor objNameMsDnM = new MsDotNetMentor(“Gaurav Arora”); //(B)
}


}


(A) From above : the sequence of invoking a constructor is first public MsDotNetHeaven() and then public MsDotNetMentor()
(B) From above : the sequence of invoking a constructor is public MsDotNetHeaven(String strName)and then public MsDotNetMentor(String strName)

Note:

  1. A static constructor should not be declared with any access modifier.

  2. A static constructor does not accept parameters

  3. A static constructor is called automatically.

  4. There is no way to call a static constructor directly.

  5. Can’t stop the execution of Static constructor



Due to the scope of this article it might be possible that something I forgot please remind me if any :

Important :

  1. Constructor is nothing but a special method, which initializes the class or its task to initialize the object of it class.

  2. Its name must be same as the name of class

  3. This is a special method as constructors do not have return types, not even void

  4. Constructor cannot return any value because they didn’t have any return type.

  5. Constructor can’t be get inherited, although a derived class can class the base class constructor.

  6. A class has atleast one constructor also known as default constructor [a constructor without parameter]

  7. You have to explicitly write a default constructor while Overloading constructors.

  8. Concept declaring multiple constructors of a class with different sets of parameters known as Constructor overloading.

  9. A constructor can be called another constructor using this()

No comments:

Post a Comment