Force static constructor to run multiple times

177 Views Asked by At

This is supposedly the way to force a static constructor to run multiple times:

typeof(Foo).TypeInitializer.Invoke(null, null);

That does not work for me. See this dotnetfiddle, example which has this:

using System;

public static class Foo
{
    static Foo()
    {
        Console.WriteLine("inside cctor");
    }

    public static void Run() { }
}

public class Program
{
    public static void Main()
    {
        Foo.Run();                                      // runs cctor
        typeof(Foo).TypeInitializer.Invoke(null, null); // does not run cctor
        typeof(Foo).TypeInitializer.Invoke(null, null); // does not run cctor
        typeof(Foo).TypeInitializer.Invoke(null, null); // does not run cctor
    }
}

That prints "inside cctor" only once. I expected it to run multiple times.

1

There are 1 best solutions below

0
On

As far as I am aware, NET6 will not run the static constructor more than once no matter whether you use the TypeInitializer method or the System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor method, whereas Net Core and Net Framework will run it more than once. I guess you could post a request on the dotnet runtime github project.