Call Static Class Constructor

Many of us have been told we can't call the static class constructor explicitly, because we can't create the instance of the static class. But actually, yes, we can call it explicitly using reflection.
  1. Add "System.Reflection" namespace to use reflection class members.
    1. using System.Reflection;  
  2. Create the static class with the constructor.
    1. staticclass CallMeIfYouCan {  
    2.     static CallMeIfYouCan() {  
    3.         Console.WriteLine("Hacked!");  
    4.     }  
    5. }  
  3. Using the following code snippet we can call the static class constructor explicitly.
    1. Type staticClassInfo = typeof(CallMeIfYouCan);  
    2. var staticClassConstructorInfo = staticClassInfo.TypeInitializer;  
    3. staticClassConstructorInfo.Invoke(null,null);  
    4. Console.ReadKey();  
  4. And here we get the constructor call hit.
Happy Coding :)