In the msdn guidance on Equals override, why the cast to object in the null check?

后端 未结 3 1217
南方客
南方客 2020-12-04 02:37

I was just looking at the Guidelines for Overloading Equals() on msdn (see code below); most of it is clear to me, but there is one line I don\'t get.

if ((S         


        
相关标签:
3条回答
  • 2020-12-04 02:47

    The == operator may be overridden, and if it is, the default reference comparison may not be what you get. Casting to System.Object ensures that calling == performs a reference equality test.

    public static bool operator ==(MyObj a, MyObj b)
    {
      // don't do this!
      return true;
    }
    
    ...
    MyObj a = new MyObj();
    MyObj b = null;
    Console.WriteLine(a == b); // prints true
    Console.WriteLine((object)a == (object)b); // prints false
    
    0 讨论(0)
  • 2020-12-04 02:59

    I suppose, since the article also talks about overriding operator==, that it's forcing it to use the == operator defined on Object rather than any overloaded operator in the current class.

    0 讨论(0)
  • 2020-12-04 03:00

    I prefer using object.ReferenceEquals(a, b) in this ambiguous context to force reference comparison because it makes the intent clear while preserving the semantics precisely (in fact, ReferenceEquals is implemented like that).

    0 讨论(0)
提交回复
热议问题