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
Object.Equals(x, y)will:xandyare both nullxoryis nullx.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 objectxoryrefers to will be invoked.ReferenceEqualswill not call the polymorphicEqualsmethod. It just compares references for equality. For example: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 usingReferenceEqualsin my experience is when you’re implementing==:Here you really don’t want to call the
==implementation, because it would recurse forever – you want the very definite reference equality semantics.