2

Having static constructor, even just empty, changes the initialization flow.

in case we have a logger class just for logging

class Logger
{
    public Logger(string text) => Console.WriteLine(text);
}

and a class with a static field with default initialization

class TestClass
{
    public static Logger StaticLogger = new Logger("StaticLogger");
}

in the console app after we instantiate TestClass, "StaticLogger" is not written on the console window.

class Program
{
    static void Main(string[] args)
    {
        new TestClass();
    }
}

But if we add an empty static constructor in our TestClass

class TestClass
{
    public static Logger StaticLogger = new Logger("StaticLogger");
    static TestClass()
    {
    }
}

After instantiation of the TestClass, now the "StaticLogger" is written on the console window.

Why does static constructor change this behaviour?

I tested with .NET core 2.1

mister_giga
  • 560
  • 1
  • 15
  • 37
  • 1
    As far as I'm aware, static members are only guaranteed to be initialized on or before the first time you use them. [This goes into it more](https://stackoverflow.com/questions/1405709/what-is-the-static-variable-initialization-order-in-c). – ProgrammingLlama Oct 18 '18 at 07:40
  • If you want to read more about the rules of static variable initializers, you can find a copy of the C# specification and read section 10.5.5.1, it contains a bit more information than Jon posts in his answer (which is a bit more focused than your question). – Lasse V. Karlsen Oct 18 '18 at 07:52
  • @LasseVågsætherKarlsen if you want to reopen the question and answer it from the specs, i think that would be worthy. Though without the specs i think my Skeets answer is a good candidate – TheGeneral Oct 18 '18 at 07:56
  • Take a look here https://stackoverflow.com/questions/33709210/static-field-is-initialized-later-when-the-class-has-a-static-constructor. If you want a bit more then read this article from Mr. Skeet - http://csharpindepth.com/Articles/General/Beforefieldinit.aspx – Ofir Winegarten Oct 18 '18 at 08:00
  • No, the duplicate is good, I just thought the quote from 10.5.5.1 at the bottom of Jons answer to be a bit short for this question here, but it *does* answer it. – Lasse V. Karlsen Oct 18 '18 at 08:25

0 Answers0