2

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?

arch-imp
  • 217
  • 3
  • 12

1 Answers1

8

You can replace the whole function with

return date.GetValueOrDefault() < MaxDate && Date > MinDate;

GetValueOrDefault() will reutnr an empty DateTime (which is DateTime.MinValue) if it's null, and that won't be > MaxDate.

You can write that explicitly too:

return (date ?? DateTime.MinValue) < MaxDate && Date > MinDate;

However, you don't even need that:

return Date > MinDate && date < MaxDate;

Nullable types have lifted comparison operators that return false if an argument is null.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I guess my desire for using the null-coalescing operator was kind of a red herring. Your last example is exactly what I was looking for. Thanks. – arch-imp Nov 08 '11 at 15:29