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.
- Add "System.Reflection" namespace to use reflection class members.
- using System.Reflection;
- Create the static class with the constructor.
- staticclass CallMeIfYouCan {
- static CallMeIfYouCan() {
- Console.WriteLine("Hacked!");
- }
- }
- Using the following code snippet we can call the static class constructor explicitly.
- Type staticClassInfo = typeof(CallMeIfYouCan);
- var staticClassConstructorInfo = staticClassInfo.TypeInitializer;
- staticClassConstructorInfo.Invoke(null,null);
- Console.ReadKey();
- And here we get the constructor call hit.

Happy Coding :)

Vilas SagarPosted Apr 19, 2022, 2:54 AM
Very Nice article
Aman AgarwalPosted Sep 19, 2018, 4:02 AM
Why it is called ctor 2 times?
Jitendra PATELPosted Sep 5, 2018, 5:38 AM
Nice Article
Rajesh KumarPosted Aug 31, 2018, 8:16 AM
Same question is replied by Jon Skeet : https://stackoverflow.com/a/2524938/392526
Hiten PandyaPosted Aug 30, 2018, 11:32 PM
Superb it's a very cool trick. One of the great article I have read. Thanks for sharing :)