How can I get the ConstructorInfo for a static constructor?
public class MyClass
{
public static int SomeValue;
static MyClass()
{
SomeValue = 23;
}
}
I’ve tried the following and failed….
Type myClass = typeof (MyClass);
// throws exception
myClass.TypeInitializer.Invoke(null);
// returns null (also tried deleting BindingFlags.Public
ConstructorInfo ci = myClass.GetConstructor(
BindingFlags.Static | BindingFlags.Public,\
System.Type.DefaultBinder,
System.Type.EmptyTypes,
null);
// returns empty array
ConstructorInfo[] clutchingAtStraws = myClass.GetConstructors
(BindingFlags.Static | BindingFlags.Public);
Use
myClass.TypeInitializer.Invoke(null, null).I’ve just tried this and it worked fine.
I would strongly recommend that you don’t do this, however – it violates a type expecting the static constructor to only be executed once. Use
RuntimeHelpers.RunClassConstructoras per Oliver’s answer if you’re just trying to ensure a class is initialized.