Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to handle nullable types

Tags:

c#

comparison

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?

like image 991
pikausp Avatar asked Mar 16 '26 18:03

pikausp


2 Answers

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
}
like image 106
keyboardP Avatar answered Mar 22 '26 05:03

keyboardP


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:

  1. If both values are null, throw an exception.
  2. If either A or B is null, return the other.
  3. If neither A or B is null, return whichever is less than the other.
like image 22
Scorpion Avatar answered Mar 22 '26 06:03

Scorpion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!