Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take the greater of two nullable values

Tags:

c#

nullable

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?

like image 361
Paul Turner Avatar asked May 01 '15 10:05

Paul Turner


3 Answers

In one line using the null coalescing operator:

int? c = a > b ? a : b ?? a;
like image 69
Nils O Avatar answered Oct 24 '22 14:10

Nils O


This works for any nullable:

Nullable.Compare(a, b) > 0 ? a : b;
like image 74
romanoza Avatar answered Oct 24 '22 15:10

romanoza


These lines show the necessary logic with a small trick:

if (a == null) return b; // handles b== null also
if (b == null) return a;
// now a!=null, b!=null
return Math.Max(a.Value, b.Value);

or in one line using ?: (exactly the same logic)

 return a == null ? b : b == null ? a : Math.Max(a.Value, b.Value);


Edit

While the answer above is interesting for educational purposes it is not the recomended way to solve this problem. The recomended way is to not reinvent the wheel instead find the matching wheel:

As @roman pointed out there exists a Nullable.Compare() method which makes this much more readable:

return Nullable.Compare(a, b) > 0 ? a : b;
like image 61
DrKoch Avatar answered Oct 24 '22 14:10

DrKoch