How does String.Equals(a,b) not produce a StackOverflowException?

C#.Net

C# Problem Overview


While examining the String == operator, I noticed that it calls String.Equals(string a, string b), meaning it's just a pass-through.

Examining the String.Equals(string a, string b) method, I see that it does an equality check using the == operator. How is this actually working and not causing a StackOverflowException when doing something like "x" == "x" or "x" == "y"?

Update: I let JetBrains know and they made it a critical priority for dotPeek. https://youtrack.jetbrains.com/issue/DOTP-6789

I also added an issue on ILSpy's GitHub repo.

String Equality

C# Solutions


Solution 1 - C#

Your decompiler has a bug. The real code doesn't check a == b, it checks (Object)a == (Object)b, bypassing the overloaded operator.

Solution 2 - C#

Here is the real code from Microsoft. Operator == is implemented as

public static bool operator == (String a, String b) {
   return String.Equals(a, b);
}

operator == calls String.Equals which is implemented as:

public static bool Equals(String a, String b) {
    if ((Object)a==(Object)b) {
        return true;
    }

    if ((Object)a==null || (Object)b==null) {
        return false;
    }

    if (a.Length != b.Length)
        return false;

    return EqualsHelper(a, b);
}

As you see, the comparison for string equality is done using if ((Object)a==(Object)b) casting the string to object and then doing the comparison. So this will not call the overloaded operator == in string class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDustin DavisView Question on Stackoverflow
Solution 1 - C#user743382View Answer on Stackoverflow
Solution 2 - C#CriketerOnSOView Answer on Stackoverflow