0

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.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 3
    I'm no Eric Lippert or Jon Skeet, but I can't imagine why you would need to do this. Can you just use a non-static class? – Crowcoder Apr 10 '22 at 01:04
  • @Crowcoder I need this for configuring things in unit tests. I'd obviously never do this in production code. :) – lonix Apr 10 '22 at 01:27
  • Regardless, this is the recommended approach in many highly upvoted questions - but it doesn't work as expected. For that reason alone I'm very curious to learn why it fails. – lonix Apr 10 '22 at 01:30
  • Test frameworks, as far as I know, typically have a way to run code upon Test Initialize. See if you can use that to start fresh on your static class before each test case. – Crowcoder Apr 10 '22 at 01:30
  • @Crowcoder Thanks for that - yes that's what I typically do (lean on the test framework). But in this case I'm working with someone else's code and have to jump through hoops. In such cases reflection is quite useful. – lonix Apr 10 '22 at 01:34

1 Answers1

0

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.

Wyrm
  • 11
  • 2