Dead account Dead account - 14 days ago 10
C# Question

How do I invoke a static constructor with reflection?

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);

Answer

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.RunClassConstructor as per Oliver's answer if you're just trying to ensure a class is initialized.