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??
The proper way to do this is:
return EqualityComparer<T>.Default.Equals(value, default(T))
No boxing. You could even define an extension method like this:
public static void bool IsDefault<T>(this T value)
{
return EqualityComparer<T>.Default.Equals(value, default(T));
}
.. and invoke it like this:
return entry.IsDefault();
Though, I personally don't care for extension methods on T (e.g. this object IsNull()) since it hampers readability sometimes.
If boxing isn't an issue, you could just use:
object.Equals(value, default(T))
When I need to test if the value is NULL I use the method below. I typically use this when calling methods that take any type but not nulls such as the Cache.
public static bool IsNull<T>(this T value)
{
var type = typeof(T);
return (type.IsClass || Nullable.GetUnderlyingType(type) != null)
&& EqualityComparer<T>.Default.Equals(value, default(T));
}
A bit of boxing will do the job just fine.
static bool IsNullOrDefault<T>(T value)
{
return ((object)default(T)) == null ?
((object)value) == null :
default(T).Equals(value);
}
Best thing I can think of at the moment is:
return value == null || value.Equals(default(T));
Edit:
Apparently, there's a static object.Equals
method I was not aware of:
return object.Equals(value, default(T));
This is better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With