문제

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

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top