160

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

1
  • The free .NET Reflector (v6) displays it "wrong" in C# (i.e. it just shows a == b), but correct in VB.NET: a Is b.
    – Mark Hurd
    Dec 17, 2014 at 0:32

2 Answers 2

218

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

11
  • 4
    @Aravol true, but the source has only recently been released Dec 10, 2014 at 21:05
  • 2
    It's pretty obfuscated code in any case though. A simple object.ReferenceEquals(a,b) would be much clearer..
    – Voo
    Dec 10, 2014 at 21:17
  • 1
    @Voo I would argue that the current version is clearer. You don't need to know anything about object.ReferenceEquals with the cast version (e.g., what if a is null?), and, as long as you know what casting is, it's certainly not obfuscated.
    – wchargin
    Dec 11, 2014 at 2:55
  • 73
    "Your decompiler has a bug". Drops the mic.
    – espinchi
    Dec 11, 2014 at 5:46
  • 1
    @Voo My guess: MS consider (Object)a == (Object)b and Object.ReferenceEquals(a, b) about equally readable, but it wouldn't surprise me if Object.ReferenceEquals(a, b) just has a slight chance of not getting inlined if the maximum inline depth is reached. MS does a lot of micro-optimisations, since most tight loops in user code do end up calling MS code.
    – user743382
    Dec 11, 2014 at 20:49
50

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.