Wednesday, January 24, 2007

Constructors in c#

There are two types of constructors in C#
instance constructor or non-static constructor
Class constructor (.cctor) or static constructor


Instance constructor is used to create an instance of the class by providing new keyword. It can take parameters (parameterized constructor). The access modifier of the instance constructor has to be public and there should not be any return type.

Static constructor is used to initialize static members of the class and is called when the class is referenced first time. Static constructor does not take any parameters and it does not have any access modifiers. From static constructor you cannot access non-static members.

As I said above, static constructor is used to initialize static members. It is used when we would like to initialize static members depending on some condition, and that condition can be kept in static constructor. This cannot be achieved if we initialize the static members at time of declaration. The static constructor of the class gets executed first whenever you try calling any static member or creating instance of the class.

No comments:

Post a Comment