Tuesday, January 18, 2011

Static Constructor in C#

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Properties of Static Constructor:
  1. Static constructor can't have access modifiers like Public,Private, Protected.
  2. It does not accept parameters.
  3. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  4. A Static constructor can be called directly.
  5. Static constructor can only access static members.
  6. The user has no control on when the static constructor is executed in the program.

Ex:

public class MYStaticClass
{

  // Static constructor:

  static MYStaticClass()
  {
   System.Console.WriteLine("Static constructor called.");
  }

  public static void StaticMethod()
  {
   System.Console.WriteLine("StaticMethod is called.");
  }
}



class TestClass
{
  private void Test()
  {
   // Call to static method.
   MYStaticClass.StaticMethod();

  }

}




//Output:
//Static constructor called.
//StaticMethod is called.



Regards,

Mahesh Bagul

No comments:

Post a Comment