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?
In one line using the null coalescing operator:
int? c = a > b ? a : b ?? a;
This works for any nullable:
Nullable.Compare(a, b) > 0 ? a : b;
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);
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;
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