问题
Almost every time I want to check object's equality to null
I use the normal equality check operation
if (obj == null)
Recently I noticed that I'm using the Object.Equals()
more often
if (Object.Equals(obj, null))
and while reading about null checking I fount this Is ReferenceEquals(null, obj) the same thing as null == obj?
if (ReferenceEquals(null, obj))
Whats the difference? and where/when to use each one? plus I found that the last two checks look like the same according to their summary
回答1:
Object.Equals(x, y)
will:
- Return true if
x
andy
are both null - Return false if exactly one of
x
ory
is null - Otherwise call either
x.Equals(y)
ory.Equals(x)
- it shouldn't matter which. This means that whatever polymorphic behaviour has been implemented by the execution-time type of the objectx
ory
refers to will be invoked.
ReferenceEquals
will not call the polymorphic Equals
method. It just compares references for equality. For example:
string x = new StringBuilder("hello").ToString();
string y = new StringBuilder("hello").ToString();
Console.WriteLine(Object.Equals(x, y)); // True
Console.WriteLine(Object.ReferenceEquals(x, y)); // False
Console.WriteLine(x == y); // True due to overloading
Now if you're only checking for nullity, then you don't really want the polymorphic behaviour - just reference equality. So feel free to use ReferenceEquals
.
You could also use ==
, but that can be overloaded (not overridden) by classes - it is in the case of string, as shown above. The most common case for using ReferenceEquals
in my experience is when you're implementing ==
:
public bool operator ==(Foo x1, Foo x2)
{
if (ReferenceEquals(x1, x2))
{
return true;
}
if (ReferenceEquals(x1, null) || ReferenceEquals(x2, null))
{
return false;
}
return x1.Equals(x2);
}
Here you really don't want to call the ==
implementation, because it would recurse forever - you want the very definite reference equality semantics.
来源:https://stackoverflow.com/questions/6993481/whats-the-difference-between-object-equalsobj-null-and-obj-null