Forcing a static constructor to be called

suggest change

A 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents