i am trying to determine if there is a difference between 2 nullable dates . . is there a more elegant ways instead of this:
if (newDate.HasValue && (!oldDate.HasValue || (oldDate.HasValue && oldDate.Value.Date != mewDate.Value.Date)))
i am trying to determine if there is a difference between 2 nullable dates . . is there a more elegant ways instead of this:
if (newDate.HasValue && (!oldDate.HasValue || (oldDate.HasValue && oldDate.Value.Date != mewDate.Value.Date)))
The C# compiler automatically lifts logical operators like ==
and !=
over nullalbe types, so you can usually compare them directly instead of checking HasValue
. In this case, you can compare with !=
once you have checked that newDate
is not null.
if(newDate.HasValue && newDate != oldDate)
It is described in the specification:
7.3.7 Lifted operators
Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types.
For the equality operators == != a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool.The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.