private class StaticInitTester
{
static StaticInitTester() {
}
private StaticInitTester()
{
var isNotNull = _mappingFunc != null ? "not" : "";
Console.WriteLine($"mapping func is {isNotNull} null");
}
public static StaticInitTester Instance { get; } = new StaticInitTester();
private static readonly Func<string, string> _mappingFunc = s => s.ToString();
}
[TestMethod]
public void TestStaticInitialization()
{
Console.WriteLine(StaticInitTester.Instance);
}
The output is actually "mapping func is null"
That surprised me since I was under the impression that all static initialization should have already completed once in the non-static constructor of StaticInitTester. When I move the line -
private static readonly Func<string, string> _mappingFunc = s => s.ToString();
To the top of the class then I get
"mapping func is not null"
So , the location of this line seems to be affecting the result.
Is this behavior documented / what's the explanation to this behavior ?