I need to check a generic object for null, or default(T). But I have a problem… Currently I have done it like this:
if (typeof(T).IsValueType) { if(default(T).Equals(thing)) // Do something else // Do something else } else { if(thing == null) // Do something else // Do something else }
But then I end up repeating myself… which I don’t like. The problem is the following:
thing == null;
Here ReSharper warns about Possible compare of value type with ‘null’.
thing == default(T);
Here I get compiler error: Cannot apply operator ‘==’ to operands of type ‘T’ and ‘T’.
thing.Equals(null|default(T));
thing can obviously be null (that’s why I have to check!), so will cause NullReferenceException.
null|default(T).Equals(thing);
null and default(T) is very often null as well…
Is there a clean way to do this??
If boxing isn’t an issue, you could just use: