My approach is to do
(object)item == null
upon which I'm relying on object's own equality operator which can't go wrong. Or 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;
}
or to handle more cases, may be:
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null || obj == DBNull.Value;
}
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
which means I have one consistent/not-error-prone style of checking for nulls throughout. I also have found (object)item == null is very very very slightly faster than Object.ReferenceEquals(item, null), 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?
answered 2012-12-16T08:13:26.553