Nullable types: better way to check for null or zero in c#

I like if ((item.Rate ?? 0) == 0) { }

Update 1:

You could also define an extension method like:

public static bool IsNullOrValue(this double? value, double valueToCheck)
{
    return (value??valueToCheck) == valueToCheck;
}

And use it like this:

if(item.IsNullOrValue(0)){} // but you don't get much from it


Using generics:

static bool IsNullOrDefault<T>(T value)
{
    return object.Equals(value, default(T));
}

//...
double d = 0;
IsNullOrDefault(d); // true
MyClass c = null;
IsNullOrDefault(c); // true

If T it's a reference type, value will be compared with null ( default(T) ), otherwise, if T is a value type, let's say double, default(t) is 0d, for bool is false, for char is '\0' and so on...


Although I quite like the accepted answer, I think that, for completeness, this option should be mentioned as well:

if (item.Rate.GetValueOrDefault() == 0) { }

This solution

  • does not require an additional method,
  • is faster than all the other options, since GetValueOrDefault is a single field read operation¹ and
  • reads easier than ((item.Rate ?? 0) == 0) (this might be a matter of taste, though).

¹ This should not influence your decision, though, since these kinds of micro-optimization are unlikely to make any difference.

Tags:

C#

Null

Zero