Updated answer
As of C# 7.0 is you can use:
item is null
should be the simplest and most foolproof way. It's same as ReferenceEquals
check.
Old answer:
1)
Object.ReferenceEquals(item, null)
This is a good way. Not as concise as I would love, but still great and tells u the intent exactly.
2)
item == null
item != null
There is nothing wrong with this (which is the most elegant) if you are sure ==
and subsequently !=
is overloaded correctly. Its easy to write (overload) bad equality operators (and often done). But the real trouble is when you are trying to overload ==
operator in a class (lets say of value semantic). You cant use ==
for null checks inside ==
overloading function of the class since that will cause an infinite recursion. To have one consistent style, I rely on something else.
3)
Object.Equals(item, null)
Again it internally does a ReferenceEquals
so there is not much point, but if it semantically makes more sense to you, then go with this.
4)
My approach is to do
(object)item == null
upon which I'm relying on object
's own equality operator which can't go wrong. Not so readable so I just wrap in a custom extension method and an overload:
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null;
}
public static bool IsNull<T>(this T? obj) where T : struct
{
return !obj.HasValue;
}
It makes more sense since I will need to check against DBNull
s too often. So now I have one consistent style all over!
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null || obj == DBNull.Value;
}
(Do not take off the (object)
casting as that's what will prevent infinite recursion when overloading ==
as stated before)
Additionally the constraint prevents IsNull
on value types. Now its as sweet as calling
object obj = new object();
Guid? guid = null;
bool b = obj.IsNull(); // false
b = guid.IsNull(); // true
2.IsNull(); // error
I also have found (object)item == null
is very very very slightly faster than Object.ReferenceEquals(item, null)
or object.Equals(,)
for that matter, but only if it matters (I'm currently working on something where I've to micro-optimize everything!).
To see a complete guide on implementing equality checks, see What is "Best Practice" For Comparing Two Instances of a Reference Type?