Explicitly call static constructor

meetjaydeep picture meetjaydeep · Jul 17, 2012 · Viewed 19.3k times · Source

I want to write unit test for below class.
If name is other than "MyEntity" then mgr should be blank.
Negative Unit test
Using Manager private accessor I want to change name to "Test" so that mgr should be null. And then will verify the mgr value. To achieve this, I want to explicitly call the static constructor but when I call the static constructor using

Manager_Accessor.name = "Test"
typeof(Manager).TypeInitializer.Invoke(null, null); 

name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.

public class Manager
{        
        private static string name= "MyEntity";

        private static object mgr;

        static Manager()
        {
            try
            {
                mgr = CreateMgr(name);
            }
            catch (Exception ex)
            {
                mgr=null;
            }
        }
}

Answer

Tobias Knauss picture Tobias Knauss · Apr 8, 2015

As I found out today, the static constructor CAN be called directly:

from another Stackoverflow post

The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (ie. reflection), you can use:

Type type = ...;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);  

I had to add this code to my application to work around a possible bug in the .net 4.0 CLR.