Wednesday, October 21, 2009

Static Constructor in C#

C# supports following two types of constructor:
  1. Class constructor (static constructor)
  2. Instance constructor (non-static constructor)
Static constructor 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.
public class StaticTestClass1(){
static StaticTestClass1(){
//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.
  •  Static constructor may only access the static members of the class.

No comments: