Given the method:
public static bool IsDateValid(DateTime? date)
{
if (date.HasValue ? date.GetValueOrDefault() < MinDate : false)
{
return false;
}
return date.GetValueOrDefault() < MaxDate;
}
Is it possible to rewrite the if statement such that it uses the null-coalescing operator?
You can replace the whole function with
GetValueOrDefault()
will reutnr an emptyDateTime
(which isDateTime.MinValue
) if it's null, and that won't be> MaxDate
.You can write that explicitly too:
However, you don't even need that:
Nullable types have lifted comparison operators that return false if an argument is null.