Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Alternative to GenericType == null

Tags:

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??

like image 656
Svish Avatar asked Feb 19 '09 14:02

Svish


5 Answers

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.

like image 115
Jason Avatar answered Sep 23 '22 04:09

Jason


If boxing isn't an issue, you could just use:

object.Equals(value, default(T))
like image 29
Jeff Yates Avatar answered Sep 23 '22 04:09

Jeff Yates


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));

}
like image 25
Damien McGivern Avatar answered Sep 23 '22 04:09

Damien McGivern


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);
    }
like image 30
Anton Gogolev Avatar answered Sep 22 '22 04:09

Anton Gogolev


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.

like image 39
configurator Avatar answered Sep 25 '22 04:09

configurator