Changed behavior of string.Empty (or System.String::Empty) in .NET 4.5

后端 未结 3 1293
温柔的废话
温柔的废话 2020-12-05 01:48

Short version:

The C# code

typeof(string).GetField(\"Empty\").SetValue(null, \"Hello world!\");
Console.WriteLine(string.Empty);
         


        
3条回答
  •  遥遥无期
    2020-12-05 02:48

    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

    • What are the implications of asking Reflection APIs to overwrite System.String.Empty?

提交回复
热议问题