Why casting to object when comparing to null?

后端 未结 5 1797
故里飘歌
故里飘歌 2021-01-07 21:04

While browsing the MSDN documentations on Equals overrides, one point grabbed my attention.

On the examples of this specific page, some null checks are made, and the

相关标签:
5条回答
  • 2021-01-07 21:46

    It is possible for a type to overload the == operator. The cast to object ensures that the original definition is used.

    0 讨论(0)
  • 2021-01-07 21:47

    It likely exists to avoid confusion with an overloaded == operator. Imagine if the cast did not exist and the == operator was overloaded. Now the p == null line would potentially bind to the operator ==. Many implementations of operator == simply defer to the overridden Equals method. This could easily cause a stack overflow situation

    public static bool operator==(TwoDPoint left, TwoDPoint right) {
      return left.Equals(right);
    }
    
    public override bool Equals(System.Object obj) {
        ...
        TwoDPoint p = obj as TwoDPoint;
        if ( p == null ) {  // Stack overflow!!!
            return false;
        }
    
        ...
    }
    

    By casting to Object the author ensures a simple reference check for null will occur (which is what is intended).

    0 讨论(0)
  • 2021-01-07 21:50

    As others said, the type might override the == operator. Therefore, casting to Objectis equivalent to if (Object.ReferenceEquals(p, null)) { ... }.

    0 讨论(0)
  • 2021-01-07 21:58

    I believe casting to System.Object would get you around any operator overloading that TwoDPoint might have.

    0 讨论(0)
  • 2021-01-07 22:04

    This might have been part of a larger sample where the == operator was overloaded. In that case, using obj == null could have resulted in StackOverflow if TwoDPoint.Equals(object) was invoked as part of the == definition.

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