开发者

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

开发者 https://www.devze.com 2023-01-03 13:48 出处:网络
Unless a class specifically overrides the behavior defined 开发者_运维知识库for Object, ReferenceEquals and == do the same thing... compare references.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消