简体   繁体   中英

C# Differences between operator ==, StringBuilder.Equals, Object.Equals and Object.ReferenceEquals

I have a question about Object.Equals and Equals(object) . My sample code is below:

class Program
{
    static void Main(string[] args)
    {
        var sb1 = new StringBuilder("Food");
        var sb2 = new StringBuilder("Food");
        Console.WriteLine(sb1 == sb2);
        Console.WriteLine(sb1.Equals(sb2));
        Console.WriteLine(Object.Equals(sb1, sb2));
        Console.WriteLine(Object.ReferenceEquals(sb1, sb2));
        Console.ReadLine();
    }
}

The output is:

False
True
False
False

But as far as I'm concerned Object.Equals(sb1, sb2) internally calls sb1.Equals(sb2) so why does it give two different results?

You are missing another test:

Console.WriteLine(sb1.Equals((object)sb2)); // False!

StringBuilder does not override Equals(object) , it overloads it with another Equals(StringBuilder) .

Object.Equals(object, object) is calling Equals(object) , so the result is false.

You are using 4 different methods of comparison, result in different results:

  • Operator == will by default do a check if the references are equal. In this case you have two instances, so they do have two different references. The behavior of == can overridden by any type (like string has its own method of comparison), but in case of the StringBuilder it is not.
  • Method StringBuilder.Equals(StringBuilder) will compare with another StringBuilder and compares some inside values. These values are, in your case, the same. Strange thing is that StringBuilder does not override the method StringBuilder.Equals(object) to apply the same logic.
  • Method object.Equals(object, object) will try to call the method .Equals(object) of one of the objects. In this case: StringBuilder.Equals(object) which, as I said, did not have the logic to compare the values. Resulting in just a compare of the references of both instances.
  • Object.ReferenceEquals will just compare the references.

For more info, see:

StringBuilder.equals does not compare the objects but rather from MSDN :

"True if this instance and sb have equal string , Capacity , and MaxCapacity values; otherwise, false."

The rest of the checks you're doing compare the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM