Friday 27 January 2012

What is a static constructor?

Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
  static SomeClass()
  {
     //Static members may be accessed from here
     //Code for Initialization
   }
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?

No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

No comments:

Post a Comment