Search code examples
c#nullable

Take the greater of two nullable values


Suppose I have two nullable integers:

int? a = 10;
int? b = 20;

I want to take the biggest, non-null value, such that if both values are null, the result is null.

I could write something long-winded such as:

int? max;
if (a == null)
{
    max = b;
}
else if (b == null)
{
    max = a;
}
else
{
    max = a > b ? a : b;
}

This feels a little too clunky (and possibly error-prone) for my liking. What's the simplest way to return the greater value, which also accounts for the possibility of null values?


Solution

  • This works for any nullable:

    Nullable.Compare(a, b) > 0 ? a : b;