Search code examples
c#nullablecomparison-operatorsdatetimeoffset

Best way to compare nullable DateTimeOffset variables?


I have code that intends to take the largest of two DateTimeOffset? variables. I have been doing this using the following code:

return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp

However, as described by the MSDN documentation, if either of the values is null then the operation always resolves to False. This means that if a value is in firstTimestamp, and secondTimestamp is null, then null is returned where firstTimestamp should be returned.

Is there an efficient short-hand way of doing this comparison accounting for null values? The only solution I can think of is something like:

if(firstTimestamp.HasValue && secondTimestamp.HasValue){
    return firstTimestamp > secondTimestamp ? firstTimestamp : secondTimestamp;
}else if(firstTimestamp.HasValue){
    return firstTimestamp;
}
return secondTimestamp;

Solution

  • You can use Nullable.Compare<T> method for that

    DateTimeOffset? firstTimestamp = DateTimeOffset.Now;
    DateTimeOffset? secondTimestamp = null;
    
    var result = Nullable.Compare(firstTimestamp, secondTimestamp) > 0 ? firstTimestamp : secondTimestamp;
    

    If firstTimestamp is not null and secondTimestamp is null, it returns a value, greater then 0, and vise versa. Then you can use this value in conditional operator ?: to get an expected result.