How can I run a static constructor?

mafu picture mafu · Apr 16, 2010 · Viewed 24.2k times · Source

I'd like to execute the static constructor of a class (i.e. I want to "load" the class) without creating an instance. How do I do that?

Bonus question: Are there any differences between .NET 4 and older versions?

Edit:

  • The class is not static.
  • I want to run it before creating instances because it takes a while to run, and I'd like to avoid this delay at first access.
  • The static ctor initializes private static readonly fields thus cannot be run in a method instead.

Answer

Gary Linscott picture Gary Linscott · Apr 16, 2010

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