C# Constructor

Broadly speaking, it is a method in the classwhich gets executed when its object is created. Usually we put theinitialization code in the constructor. Writing a constructor in theclass is damn simple, have a look at the following sample :

public class mySampleClass
{
public mySampleClass()
{
// This is the constructor method.
}
// rest of the class members goes here.
}

When the object of this class is instantiated this constructor will be executed. Something like this :
mySampleClass obj = new mySampleClass()
// At this time the code in the constructor will // be executed

Constructor Overloading :

C# supports overloading of constructors, thatmeans we can have constructors with different set of parameters. So ourclass can be like this :

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

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

}

public mySampleClass(int Age, string Name)
{
// This is the constructor with two parameters.
// Third Constructor
}

// rest of the class members goes here.
}

Well, note here that call to the constructor now depends on the way you instantiate the object. For example :

mySampleClass obj = new mySampleClass()
// At this time the code of no parameter
// constructor (First Constructor)will be executed

mySampleClass obj = new mySampleClass(12)
// At this time the code of one parameter
// constructor(Second Constructor)will be
// executed.

The call to the constructors is completely governed by the rules of the overloading here.

Calling Constructor from another Constructor:

You can always make the call to one constructor from within the other. 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 saythis(10), we actually mean execute the public mySampleClass(int Age)method. The above way of calling the method is called initializer. Wecan have at the most one initializer in this way in the method.

Another thing which we must know is theexecution sequence i.e., which method will be executed when. Here if Iinstantiate 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 thedefinition 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 that only this and base (we will see itfurther) keywords are allowed in initializers, other method calls willraise the error.

This is sometimes called Constructor chaining.

Huff� Simple thing made tough, but this is how it is. Anyway, let us proceed further.

Behavior of Constructors in Inheritance :

Let us first create the inherited class.

public class myBaseClass
{
public myBaseClass()
{
// Code for First Base class Constructor
}

public myBaseClass(int Age)
{
// Code for Second Base class Constructor
}

// Other class members goes here

}

public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
public myDerivedClass()
{
// Code for the First myDerivedClass Constructor.
}

public myDerivedClass(int Age):base(Age)
{
// Code for the Second myDerivedClass Constructor.
}

// Other class members goes here
}

Now what will be the execution sequence here :
If I create the object of the Derived class as
myDerivedClass obj = new myDerivedClass()

Then the sequence of execution will be
1. public myBaseClass() method.
2. and then public myDerivedClass() method.

Note: If we do not provide initializerreferring to the base class constructor then it executes the noparameter constructor of the base class.

Note one thing here : We are not making anyexplicit call to the constructor of base class neither by initializernor by the base() keyword, but it is still executing. This is thenormal behavior of the constructor.

If I create the object of the Derived class as
myDerivedClass obj = new myDerivedClass(15)

Then the sequence of execution will be
1. public myBaseClass(int Age) method.
2. and then public myDerivedClass(int Age) method.

Here the new keyword base has come intopicture. This refers to the base class of the current class. So, hereit refers to the myBaseClass. And base(10) refers to the call tomyBaseClass(int Age) method.

Also note the usage of Age variable in thesyntax : public myDerivedClass(int Age):base(Age). [ Understanding itis left to the reader. ]

Phew� lost� Anything left in constructors. Yes, Static Constructors. Ha!! Now what are they ? Let us see..

Static Constructors :
This is a new conceptintroduced in C#. By new here I mean that it was not available for theC++ developers. This is a special constructor and gets called beforethe first object is created of the class. The time of execution cannotbe determined, but it is definitely before the first object creation -could be at the time of loading the assembly.

The syntax of writing the static constructors is also damn simple. Here it is :

public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
// Other class methods goes here
}

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.

Ok fine, all the above points are fine but why is it like that? Let us go step by step here.

Firstly, the call to the static method is madeby the CLR and not by the object, so we do not need to have the accessmodifier to it.

Secondly, it is going to be called by CLR, whocan pass the parameters to it, if required, No one, so we cannot haveparameterized static constructor.

Thirdly, Non-static members in the class arespecific to the object instance so static constructor, if allowed towork on non-static members, will reflect the changes in all the objectinstances, which is impractical. So static constructor can access onlystatic members of the class.

Fourthly, Overloading needs the two methods tobe different in terms to methods definition, which you cannot do withStatic Constructors, so you can have at the most one static constructorin the class.

Now, one question raises here, can we have the two constructors as

public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
public myClass()
{
// Code for the First myDerivedClass Constructor.
}

// Other class methods goes here
}

This is perfectly valid, though doesn�t seemto be in accordance with overloading concepts. But why? Because thetime of execution of the two method are different. One is at the timeof loading the assembly and one is at the time of object creation.

FAQs Regd. Constructors :
1. Is the Constructor mandatory for the class?
Yes,It is mandatory to have the constructor in the class and that tooshould be accessible for the object i.e., it should have a properaccess modifier. Say for example we have the private constructor in theclass then it is of no use as it cannot be accessed by the object, sopractically it is no available for the object. In such conditions itwill raise an error.

2. What if I do not write the constructor?
Insuch case the compiler will try to supply the no parameter constructorfor your class behind the scene. Compiler will attempt this only if youdo not write the constructor for the class. If you provide anyconstructor ( with or without parameters ), then compiler will not makeany such attempt.

3. What if I have the constructor public myDerivedClass() but not the public myBaseClass()?
Itwill raise an error. If either the no parameter constructor is absentor it is in-accessible ( say it is private ), it will raise an error.You will have to take the precaution here.

4. Can we access static members from the non-static ( normal ) constructors?
Yes,We can. There is no such restriction on non-static constructors. Butthere is one on static constructors that it can access only staticmembers.

Reference:
1. Professional C# 2nd Edition by Wrox Publication

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!