Explicitly call static constructor

As I found out today, the static constructor CAN be called directly: from another Stackoverflow post The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (ie. reflection), you can use: Type type = …; System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle); I had to add this code … Read more

How to pass parameter to static class constructor?

Don’t use a static constructor, but a static initialization method: public class A { private static string ParamA { get; set; } public static void Init(string paramA) { ParamA = paramA; } } In C#, static constructors are parameterless, and there’re few approaches to overcome this limitation. One is what I’ve suggested you above.

static readonly field initializer vs static constructor initialization

There is one subtle difference between these two, which can be seen in the IL code – putting an explicit static constructor tells the C# compiler not to mark the type as beforefieldinit. The beforefieldinit affects when the type initializer is run and knowing about this is useful when writing lazy singletons in C#, for … Read more

static constructors in C++? I need to initialize private static objects

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class. class StaticStuff { std::vector<char> letters_; public: StaticStuff() { for (char c=”a”; c <= ‘z’; c++) letters_.push_back(c); } // provide some way to get at … Read more