I often see in source codes the usage of if (object.ReferenceEquals(myObject, null)) for checking if myObject is null instead of if (myObject == null) which I am familiar with.
Is there any particular reason (like speed, readability, etc) for using the first way instead of the second one? Which one do you use?
Thank you in advance.
When using ReferenceEquals
you make sure that no special handling (overloaded operator for instance) is being applied. This also leads to different results if used with unbound generics.
Simple things are usually the most efficient :
(myObject == null)
is more performant
Look at this article
Take a look at this interesting article
Performance Tip: Prefer (((Object) x)== null) to Object.ReferenceEquals(x,null)
The ==
operator can be overloaded by class implementations, so it might not do a reference comparision (though it probably should with null
s). object.ReferenceEquals
can't, so it reliably always does a reference comparision.
Cheers Matthias
The ReferenceEquals method cannot be overridden and so you can always be certain that the comparison is going to compare the object references and not be passed to some override of the Equals method.
They usually have the same effect, although they compile to different things. if (myObject == null)
results in a ceq
opcode, which I'd expect to compile to quicker code. object.ReferenceEquals
is a method call like any other.
They're different when myObject
has an operator=
method; when this is present, your code calls into this method instead of using ceq
. operator=
can then do whatever it likes.
Always if (myObject == null)
unless you have a reason not to.
精彩评论