Tuesday, August 16, 2016

Static Constructor

performed once only. 
It is called automatically before the first instance is created or any static members are referenced.
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running
public class MyClass
 {
     public MyClass()
     {
         Console.WriteLine("Is Class Constructor");
     }

     static MyClass()
     {
         Console.WriteLine("Is Static Constructor");
     }

     public void method()
     {
         Console.WriteLine("Method A");
     }

     public static void methodStatic()
     {
         Console.WriteLine("Method Static");
     }
 }


 static void Main(string[] args)
 {
     MyClass classA = new MyClass();
     MyClass classB = new MyClass();
     classA.method();
     classB.method();

     MyClass.methodStatic();

     Console.ReadLine();

 }

Result :
Is Static Constructor
Is Class Constructor
Is Class Constructor
Method A
Method A
Method Static

No comments:

Post a Comment