Tuesday, 28 January 2014

Calling Constructor from another Constructor

You can always make a call to one constructor from within another. Say, for example:

public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

Very first of all, let us see what is this syntax:

public mySampleClass(): this(10)

Here, this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.
Another thing which we must know is the execution sequence i.e., which method will be executed when. Here, if I instantiate the object as:

mySampleClass obj = new mySampleClass()

Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So, practically the definition of the method:

public mySampleClass(): this(10)
{
    // This is the no parameter constructor method.
    // First Constructor
}

is equivalent to:

public mySampleClass()
{
    mySampleClass(10)
    // This is the no parameter constructor method.
    // First Constructor
}

Note: Above (just above this line) code is mentioned there for pure analogy and will not compile. The intention here is to tell the flow of execution if initializers are used.
We cannot make an explicit call to the constructors in C#, treating them as if any simple method, for example: statement mySampleClass(10) in the above code will not work. The only way you can call one constructor from another is through initializers.
For the VB.NET programmers: you can make the call to another constructor of the same class by the syntaxMe.New(param list), but it should be the first line of your calling constructor method. So ultimately, the code of the called constructor runs prior to the code of the calling constructor, which is same as initializers here.
Note that only this and base (we will see it further) keywords are allowed in initializers, other method calls will raise an error.
This is sometimes called Constructor chaining.

No comments:

Post a Comment