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:
Post a Comment