“FatalExecutionEngineError was detected” when using Console.Writeline after redefining String.Empty-Collection of common programming errors

If we look at the program

class Program
{
    static void Main()
    {
        Console.WriteLine("{}", "");
    }
}

then it will fail with an FormatException with the error message Input string was not in a correct format.

However when we insert typeof(string).GetField("Empty").SetValue(null, " "); before the line with Console.WriteLine then 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 at System.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(string fileName = " mscorlib.resources") (notice the space in front of mscorlib.resources).

The reason for this is that ManifestBasedResourceGroveler uses the metode GetResourceFileName of ResourceManager to find the resource file. And in GetResourceFileName we use a StringBuilder to construct the filename and the constructor of StringBuilder starts with String.Empty.

public StringBuilder(int capacity)
    : this(String.Empty,capacity){
}