Dead account Dead account - 1 year ago 127
C# Question

How do I invoke a static constructor with reflection?

How can I get the

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

// 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download