How can I run a static constructor?
Also you can do this:
type.TypeInitializer.Invoke(null, null);
The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (i.e. reflection), you can use RunClassConstructor
:
Type type = ...;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
Just reference one of your static fields. This will force your static initialization code to run. For example:
public class MyClass
{
private static readonly int someStaticField;
static MyClass() => someStaticField = 1;
// any no-op method call accepting your object will do fine
public static void TouchMe() => GC.KeepAlive(someStaticField);
}
Usage:
// initialize statics
MyClass.TouchMe();