I’m trying (for fun) to redefine String.Empty to be a single space ““. Why does this break the CLR framework?
Message:
The runtime has encountered a
fatal error. The address of the error
was at 0x5814b976, on thread 0xf40.
The error code is 0x80131623. This
error may be a bug in the CLR or in
the unsafe or non-verifiable portions
of user code. Common sources of this
bug include user marshaling errors for
COM-interop or PInvoke, which may
corrupt the stack.
How to reproduce:
class Program
{
static void Main()
{
typeof(string).GetField("Empty").SetValue(null, " ");
Console.WriteLine("{}", "");
}
}
If we look at the program
then it will fail with an
FormatExceptionwith the error messageInput string was not in a correct format.However when we insert
typeof(string).GetField("Empty").SetValue(null, " ");before the line withConsole.WriteLinethen the code fails when it tries to look up that error message. If we look at the full stacktrace (including “Show external code”) then we see that the code fails atSystem.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(string fileName = " mscorlib.resources")(notice the space in front of mscorlib.resources).The reason for this is that
ManifestBasedResourceGroveleruses the metodeGetResourceFileNameofResourceManagerto find the resource file. And inGetResourceFileNamewe use aStringBuilderto construct the filename and the constructor ofStringBuilderstarts withString.Empty.