1

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)))
Andy G
  • 19,232
  • 5
  • 47
  • 69
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • It looks like you've got some relatively complicated and asymmetric rules there, so I'm not really surprised that you need to write them out in full. – Jon Skeet Sep 02 '13 at 21:21

1 Answers1

1

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.

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Possibly he simply meant `if (newDate != oldDate)`. I know his expression wasn't equivalent to that, but that is all it takes to check if there is any "difference". – Jeppe Stig Nielsen Sep 03 '13 at 00:41