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


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

All Answers
  • Kelly Lee

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

  • Translate

    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.