Short version:
The C# code
typeof(string).GetField(\"Empty\").SetValue(null, \"Hello world!\");
Console.WriteLine(string.Empty);
Because it can.
The value of these system-defined initonly
fields are global invariants for the .NET runtime. If these invariants are broken, there are no longer any guarantees whatsoever regarding the behavior.
In C++, we would probably have a rule designating this as causing undefined behavior. In .NET, it is also undefined behavior, simply by the absence of any rule saying what happens when System.String.Empty.Length > 0
. The whole specification of all layers of .NET and C# describe the behavior when System.String.Empty.Length == 0
and a whole bunch of invariants also hold.
For more information about optimizations which vary between runtimes and the implications, see the answers to