Wednesday, September 24, 2008

Constructors in C#

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)


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


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

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

Secondly, it is going to be called by CLR, who can pass the parameters to it, if required, No one, so we cannot have parameterized static constructor.

Thirdly, Non-static members in the class are specific to the object instance so static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

Fourthly, Overloading needs the two methods to be different in terms to methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.

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

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

No comments:

Post a Comment