views:

56

answers:

2

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()?

A: 

== should test to see if the reference points to the same location whereas ReferenceEquals tests to see if they contain the same data

BuildStarted
The other way around would be correct
jdehaan
I think this should be the exact opposite, tbh.
Anton
Hmm...Well after some quick tests == and ReferenceEquals produce the same results but I suppose you're right. Oh well -points for me :)
BuildStarted
This is because unless overridden the == operator usually performs a reference equality check.When overridden however, it may or may not use this. Therefore the == operator should not be used if you want to check for reference equality on immutable types.
Anton
+2  A: 

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

jdehaan
@jdehaan: Why the Golden Rule `If you want to know if two objects refer to the same instance USE ONLY ReferenceEquals`? MSDN states `For reference types other than string, == returns true if its two operands refer to the same object.` http://msdn.microsoft.com/en-us/library/53k8ybth.aspx Not challenging the Golden Rule, just want to understand it.
Eric J.
Just because it always works. The == might be wrongly implemented which makes it potentially problematic. It saved my life when I decided to make my objects immutable in a project, where == is overriden for equality not identity. So I always use ReferenceEquals if objects, not values must be compared.
jdehaan