How can I run a static constructor?

C#.NetStatic Constructor

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Just reference one of your static fields. This will force your static initialization code to run. For example:

public class MyClass
{
	private static readonly int someStaticField;

	static MyClass() => someStaticField = 1;

	// any no-op method call accepting your object will do fine
	public static void TouchMe() => GC.KeepAlive(someStaticField);
}

Usage:

// initialize statics
MyClass.TouchMe();

Solution 3 - C#

The cctor (static constructor) will be called whenever one of the following occurs;

  1. You create an instance of the class
  2. Any static member is accessed
  3. Any time before that, if BeforeFieldInit is set

If you want to explicitly invoke the cctor, assuming you have other static members, just invoke/access them.

If you are not doing anything very interesting in your cctor, the compiler may decide to mark it BeforeFieldInit, which will allow the CLR the option to execute the cctor early. This is explained in more detail here: http://blogs.msdn.com/davidnotario/archive/2005/02/08/369593.aspx

Solution 4 - C#

Also you can do this:

type.TypeInitializer.Invoke(null, null);

Solution 5 - C#

Extending Fábio's observations, the following short and complete test program exposes the JIT-sensitive details of TypeAttributes.BeforeFieldInit behavior, comparing .NET 3.5 to the latest version (as of late 2017) .NET 4.7.1, and also demonstrates the potential hazards for build type variations within each version itself.[1]

using System;
using System.Diagnostics;

class MyClass
{
	public static Object _field = Program.init();

	public static void TouchMe() { }
};

class Program
{
	static String methodcall, fieldinit;

	public static Object init() { return fieldinit = "fieldinit"; }

	static void Main(String[] args)
	{
		if (args.Length != 0)
		{
			methodcall = "TouchMe";
			MyClass.TouchMe();
		}
		Console.WriteLine("{0,18}  {1,7}  {2}", clrver(), methodcall, fieldinit);
	}
};

Below is the console output from running this program in all combinations of { x86, x64 } and { Debug, Release }. I manually added a delta symbol Δ (not emitted by the program) to highlight the differences between the two .NET versions.

>.NET 2.0/3.5 > >2.0.50727.8825 x86 Debug
>2.0.50727.8825 x86 Debug TouchMe fieldinit
>2.0.50727.8825 x86 Release fieldinit
>2.0.50727.8825 x86 Release TouchMe fieldinit
>2.0.50727.8825 x64 Debug
>2.0.50727.8825 x64 Debug TouchMe fieldinit
>2.0.50727.8825 x64 Release
>2.0.50727.8825 x64 Release TouchMe fieldinit
> >.NET 4.7.1 > >4.7.2556.0 x86 Debug
>4.7.2556.0 x86 Debug TouchMe fieldinit
>4.7.2556.0 x86 Release Δ
>4.7.2556.0 x86 Release TouchMe Δ
>4.7.2556.0 x64 Debug
>4.7.2556.0 x64 Debug TouchMe fieldinit
>4.7.2556.0 x64 Release
>4.7.2556.0 x64 Release TouchMe Δ

As noted in the intro, perhaps more interesting than the version 2.0/3.5 versus 4.7 deltas are the differences within the current .NET version, since they show that, although the field-initialization behavior nowadays is more consistent between x86 and x64 than it used to be, it's still possible to experience a significant difference in runtime field initialization behavior between your Debug and Release builds today.

The semantics will depend on whether you happen to call a disjoint or seemingly unrelated static method on the class or not, so if doing so introduces a bug for your overall design, it is likely to be quite mysterious and difficult to track down.


Notes
1. The above program uses the following utility function to display the current CLR version:

static String clrver()
{
	var s = typeof(Uri).Assembly.Location;
	return FileVersionInfo.GetVersionInfo(s).ProductVersion.PadRight(14) +
		(IntPtr.Size == 4 ? " x86 " : " x64 ") +
#if DEBUG
		"Debug  ";
#else
		"Release";
#endif
}

Solution 6 - C#

Static constructors are NOT always called when accessing a static method!

I noticed that if you call a static method in a base class, the static constructor of the super class is NOT called. This unexpected behavior has bitten many times.

Solution 7 - C#

There is no need to do this, the whole point of a static constructor is that it runs once when the class is first initialised at first access. If you want to run something on demand, then consider adding your initialisation code into a public method that is called by the constructor. You can then call this method whenever you like. But I'm not sure why you would want to do this?

Solution 8 - C#

As others have said, static constructors run automatically. If you need to be explicit, maybe you should refactor it into a static method which you can run explicitly?

Explicitly calling a static method would also, of course, ensure that the static constructor had been executed.

edit

Static constructors are run when any static members are referenced. You could simply create a dummy method called initialize which did nothing but ensure that the framework calls the static constructor.

Solution 9 - C#

I'm not exactly sure what your use case is for this, but you can force static initializers to run in a fairly hacky way using partial classes and inner classes:

The idea is to use a partial outter class with a static field that accesses another static field on the inner class. When the outter class is statically initialized, the static field initialization will kick-off the static initialization of all the inner classes:


public partial class OutterClass
{
    // When OutterClass is initialized, this will force InnerClass1 to be initialized.
    private static int _innerClass1Touched = InnerClass1.TouchMe;
	
    public static class InnerClass1
    {
        public static int TouchMe = 0;
		
        static InnerClass1()
        {
            Console.WriteLine("InnerClassInitialized");
        }
    }
}

public partial class OutterClass
{
    // When OutterClass is initialized, this will force InnerClass2 to be initialized.
    private static int _innerClass2Touched = InnerClass2.TouchMe;
	
    public static class InnerClass2
    {
        public static int TouchMe = 0;
		
        static InnerClass2()
        {
            Console.WriteLine("InnerClass2Initialized");
        }
    }
}

Then, somewhere early in your application, you just need to reference OutterClass in a way that will result in static initialization, like constructing an instance of it.

A more realistic example might be...

public interface IService
{
	void SayHello();
}

public partial class ServiceRegistry
{
	private static List<Func<IService>> _serviceFactories;
	
	private static void RegisterServiceFactory(Func<IService> serviceFactory)
	{
		// This has to be lazily initialized, because the order of static initialization
		//	isn't defined. RegisterServiceFactory could be called before _serviceFactories
		//  is initialized.
		if (_serviceFactories == null)
			_serviceFactories = new List<Func<IService>>();
			
		_serviceFactories.Add(serviceFactory);
	}
	
	public List<IService> Services { get; private set; }
	
	public ServiceRegistry()
	{
		Services = new List<IService>();
		
		foreach (var serviceFactory in _serviceFactories)
		{
			Services.Add(serviceFactory());
		}
	}
}


// In another file (ServiceOne.cs):
public class ServiceOne : IService
{
	void IService.SayHello()
	{
		Console.WriteLine("Hello from ServiceOne");
	}
}

public partial class ServiceRegistry
{
    // When OutterClass is initialized, this will force InnerClass1 to be initialized.
    private static int _serviceOneRegistryInitializer = ServiceOneRegistry.Initialize;
	
    private static class ServiceOneRegistry
    {
        public static int Initialize = 0;
		
        static ServiceOneRegistry()
        {
            ServiceRegistry.RegisterServiceFactory(() => new ServiceOne());
        }
    }
}

// In another file (ServiceTwo.cs):
public class ServiceTwo : IService
{
	void IService.SayHello()
	{
		Console.WriteLine("Hello from ServiceTwo");
	}
}

public partial class ServiceRegistry
{
    // When OutterClass is initialized, this will force InnerClass1 to be initialized.
    private static int _serviceTwoRegistryInitializer = ServiceTwoRegistry.Initialize;
	
    private static class ServiceTwoRegistry
    {
        public static int Initialize = 0;
		
        static ServiceTwoRegistry()
        {
            ServiceRegistry.RegisterServiceFactory(() => new ServiceTwo());
        }
    }
}

static void Main(string[] args)
{
	ServiceRegistry registry = new ServiceRegistry();
	foreach (var service in registry.Services)
	{
		serivce.SayHello();
	}
	
	// Output will be:
	// Hello from ServiceOne
	// Hello from ServiceTwo
	
	// No guarantee on order.
}

Why even do this? It has a very narrow use-case. It eliminates the need to have a single method that initializes and registers all the services. The case in which I personally want to eliminate that single method initialization is for code generation purposes.

Solution 10 - C#

The static constructor runs automatically the first time you access the class. There is no need (or capability) to 'run' it yourself.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmafuView Question on Stackoverflow
Solution 1 - C#Gary LinscottView Answer on Stackoverflow
Solution 2 - C#Fábio BatistaView Answer on Stackoverflow
Solution 3 - C#csauveView Answer on Stackoverflow
Solution 4 - C#zumalifeguardView Answer on Stackoverflow
Solution 5 - C#Glenn SlaydenView Answer on Stackoverflow
Solution 6 - C#ScottKView Answer on Stackoverflow
Solution 7 - C#Dan DiploView Answer on Stackoverflow
Solution 8 - C#Gabe MoothartView Answer on Stackoverflow
Solution 9 - C#Greg HanesView Answer on Stackoverflow
Solution 10 - C#RayView Answer on Stackoverflow