Static Initialization
10/22/2019
The way static fields are initialized has been changed across .net framework version. As the framework matured, static fields have become initialized more lazily.
Today I will show a quick comparison between .net472
and .netcoreapp3.0
focused on static field initialization. I will use the following application to demonstrate the issue.
class Program { static void Main(string[] args) { Console.WriteLine("Start"); var test = new Test(); test.DoWork(); Console.WriteLine("Start work"); test.DoWork2(); } } public class Test { private static readonly Logger logger = new Logger(); public Test() => Console.WriteLine("TestCtr"); public void DoWork() => Console.WriteLine("Working..."); public void DoWork2() { Console.WriteLine("Working2..."); logger.Log("Completing work"); } } public class Logger { public Logger() => Console.WriteLine("LoggerCtr"); public void Log(string message) => Console.WriteLine(message); }
As normally, someone using C# for a while you would expect static fields and class constructor (or static constructor) run and initialized before the first instance of a class being created and used. Now this is not entierly true, as we will see it in the following sections.