Is there a difference between x is null and ReferenceEquals(x, null)?

后端 未结 4 1460
悲哀的现实
悲哀的现实 2020-12-19 13:01

When I write this:

ReferenceEquals(x, null)

Visual studio suggests that the

null check can be simplified.

4条回答
  •  天命终不由人
    2020-12-19 13:37

    I noticed a lot of answers specifying that x == null, x is null, and ReferenceEquals(x, null) are all equivalent - and for most cases this is true. However, there is a case where you CANNOT use x == null as I have documented below:

    Note that the code below assumes you have implemented the Equals method for your class:

    Do NOT do this - the operator == method will be called recursively until a stack overflow occurs:

    public static bool operator ==(MyClass x1, MyClass x2)
    {
       if (x1 == null)
          return x2 == null;
    
       return x1.Equals(x2)
    }
    

    Do this instead:

    public static bool operator ==(MyClass x1, MyClass x2)
    {
       if (x1 is null)
          return x2 is null;
    
       return x1.Equals(x2)
    }
    

    Or

    public static bool operator ==(MyClass x1, MyClass x2)
    {
       if (ReferenceEquals(x1, null))
          return ReferenceEquals(x2, null);
    
       return x1.Equals(x2)
    }
    

提交回复
热议问题