Extending Fábio's observations, the following short and complete test program exposes the JIT-sensitive details of TypeAttributes.BeforeFieldInit
behavior, comparing .NET 3.5 to the latest version (as of late 2017) .NET 4.7.1, and also demonstrates the potential hazards for build type variations within each version itself.[1]
using System;
using System.Diagnostics;
class MyClass
{
public static Object _field = Program.init();
public static void TouchMe() { }
};
class Program
{
static String methodcall, fieldinit;
public static Object init() { return fieldinit = "fieldinit"; }
static void Main(String[] args)
{
if (args.Length != 0)
{
methodcall = "TouchMe";
MyClass.TouchMe();
}
Console.WriteLine("{0,18} {1,7} {2}", clrver(), methodcall, fieldinit);
}
};
Below is the console output from running this program in all combinations of { x86, x64 } and { Debug, Release }. I manually added a delta symbol Δ
(not emitted by the program) to highlight the differences between the two .NET versions.
.NET 2.0/3.5
2.0.50727.8825 x86 Debug
2.0.50727.8825 x86 Debug TouchMe fieldinit
2.0.50727.8825 x86 Release fieldinit
2.0.50727.8825 x86 Release TouchMe fieldinit
2.0.50727.8825 x64 Debug
2.0.50727.8825 x64 Debug TouchMe fieldinit
2.0.50727.8825 x64 Release
2.0.50727.8825 x64 Release TouchMe fieldinit
.NET 4.7.1
4.7.2556.0 x86 Debug
4.7.2556.0 x86 Debug TouchMe fieldinit
4.7.2556.0 x86 Release Δ
4.7.2556.0 x86 Release TouchMe Δ
4.7.2556.0 x64 Debug
4.7.2556.0 x64 Debug TouchMe fieldinit
4.7.2556.0 x64 Release
4.7.2556.0 x64 Release TouchMe Δ
As noted in the intro, perhaps more interesting than the version 2.0/3.5 versus 4.7 deltas are the differences within the current .NET version, since they show that, although the field-initialization behavior nowadays is more consistent between x86
and x64
than it used to be, it's still possible to experience a significant difference in runtime field initialization behavior between your Debug
and Release
builds today.
The semantics will depend on whether you happen to call a disjoint or seemingly unrelated static method on the class or not, so if doing so introduces a bug for your overall design, it is likely to be quite mysterious and difficult to track down.
Notes
1. The above program uses the following utility function to display the current CLR version:
static String clrver()
{
var s = typeof(Uri).Assembly.Location;
return FileVersionInfo.GetVersionInfo(s).ProductVersion.PadRight(14) +
(IntPtr.Size == 4 ? " x86 " : " x64 ") +
#if DEBUG
"Debug ";
#else
"Release";
#endif
}