Thursday, June 14, 2007

Constructor Concept in .Net + Static Constructor concept and Example

Constructor
1) A constructor is a special method whose task is to initialize the object of its class.
2) It is special because its name is the same as the class name.
3) They do not have return types, not even void and therefore they cannot return values.
4) They cannot be inherited, though a derived class can call the base class constructor.
5) Constructor is invoked whenever an object of its associated class is created.
6) Note: There is always atleast one constructor in every class. If you do not write a
constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().


Static Constructor

In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.
One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

Example of Static Constructor
Class MyClass

{

static MyClass()

{

//Initialization Code for static fields and properties.

}

}

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape