Search code examples
c#.netentity-framework-4inequality

!(ReferenceEquals()) vs != in Entity Framework 4


Unless a class specifically overrides the behavior defined for Object, ReferenceEquals and == do the same thing... compare references.

In property setters, I have commonly used the pattern

private MyType myProperty;

public MyType MyProperty
{
    set
    {
        if (myProperty != value)
        {
            myProperty = value;
            // Do stuff like NotifyPropertyChanged
        }
    }
}

However, in code generated by Entity Framework, the if statement is replaced by

    if (!ReferenceEquals(myProperty, value))

Using ReferenceEquals is more explicit (as I guess not all C# programmers know that == does the same thing if not overridden).

Is there any difference that's escaping me between the two if-variants? Are they perhaps accounting for the possibility that POCO designers may have overridden ==?

In short, if I have not overridden ==, am I save using != instead of ReferenceEquals()?


Solution

  • Here are the different semantics:

    • ReferenceEquals() must be used if you mean that the objects are exactly the same (identity check).
    • object.Equals() shall be used if you mean the objects have the same value (equality check)
    • ==() shall only be used for immutable types. Then use it to test for equality.

    Of course the inversed counterparts are meant accordingly.

    Here is a summary