What's the proper way of dealing with nullable types like 'DateTime?'? When you need to pick a smaller of 2 dates that are nullable and one of them is null, < or > won't do as comparing null to actual date results in false, so for example:
DateTime? function( DateTime? a, DateTime? b ){
return a < b ? a : b;
}
would return b if either a or b were null.
Do I have to use if-statements or is there a workaround?
Edit: I'd like not-null to be returned if one of the values is null
Edit: I'm sorry if it was confusing that I used a function as an example. It's not that I wanted to avoid using if-statements. But there's a lot of comparisms between nullable DateTimes and I'd like to avoid creating custom comparators that would require an explicti call and such.
Is it possible to override the default DateTime? comparators?
You could use Nullable.Compare.
static DateTime? GetLowerDateTime(DateTime? a, DateTime? b)
{
int val = Nullable.Compare(a, b);
if (val < 0) return a ?? b;
if (val > 0) return b ?? a;
return a; //whichever you want to return if they're equal
}
DateTime? function( DateTime? a, DateTime? b ){
if(!a.HasValue && !b.HasValue)
throw new ArgumentNullException();
else if(!a.HasValue)
return b;
else if(!b.HasValue)
return a;
return a.Value < b.Value ? a : b;
}
Logic:
null, throw an exception.null, return the other.null, return whichever is less than the other.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