Search code examples
c#.netoperatorsiequatableequals-operator

How to treat nulls in equality comparisons?


When I have to implement equality comparers for

public class SampleClass
{
    public int Prop { get; set; }
}

Should I make

null == new SampleClass() 

and

new SampleClass() == null

and

new SampleClass().Equals(null)

false?

And what about

new SampleClass() != null

Should it be also false?

UPDATE People are questioning the reasoning behind this question. It's supposed that != and == be always opposites. But if I implement the methods so all those comparisons above results in false, there will be a case where the == and != operators will result the same result. So it's a dilemma whether != should return true or false.


Solution

  • All the equality comparions with null from your example should definitely be false. The last one is also very important however:

    new SampleClass() != null
    

    This must definitely evaluate to true, because this is a common way to check if a reference variable has been initialized. If it were to evaluate to false, it might unintentionally reassign the variable all over the place, because C# developers expect a certain kind of behavior from there operators. Another example:

    SampleClass myVar = new SampleClass();
    
    // Various stuff happening here, possibly setting myVar to null
    
    if (myVar != null)
    {
        // Programmer go "WTFBBQ?" when he finds this doesn't get executed
        myVar.DoStuff();
    }
    

    Confused, the programmer changes this to:

    if (myVar == null)
    {
        myVar = new SampleClass();
    }
    
    myVar.DoStuff(); // null reference exception, huh?