Forcing a static constructor to be called
suggest changeA static constructor runs before the first use of a type. RuntimeHelpers can force that run earlier:
using System.Runtime.CompilerServices;
// ...
RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
Remark: The type initializer runs, including field initializers, not only the constructor body. If the initializer already ran, RunClassConstructor does nothing.
Potential uses: forcing initialization during the splash screen of a UI application, or ensuring that a static constructor does not fail during a unit test.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents