I have a static class with a static constructor that takes some time (10-15 seconds) to execute and fully initialize the class. In order to improve performance, I\'ve decided to
Two work-arounds:
Move the constructor code to Initialize() so you can call explicitly. And replace the code inside the constructor to just call the Initialize() method in case the static class is loaded dynamically before you've called it explicitly
public static class StaticClass
{
// actual constructor
static StaticClass()
{
Initialize();
}
// explicit "constructor"
public static void Initialize()
{
MyProperty = "Some Value";
}
public static string MyProperty { get; set; }
}
Then initialize like this if you want:
StaticClass.Initialize();
Or it will be dynamically initialized the first time it's used
Not as semantically pristine, but you can trigger the organic initialization of a static class just by consuming a property and throwing it in a temporary variable.
So just do this:
// trigger static initilaization
var dummy = StaticClass.MyProperty;
Still allows you to call it whenever you need to, but if there is some performance cost on initialization, you can try to invoke it on startup, rather than the first time the user does something that fires that code.
For another helpful outline of static initialization see: Is the order of static class initialization in C# deterministic?