6

Here is some example code:

static DateTime time;
if (time == null)
{
/* do something */
}

Since DateTime cannot be null, why does this code compile?

Edit: The issue is not just that this code will always return false,but why something like DateTime which is never null is allowed in such a comparison.

Rinus
  • 140
  • 1
  • 9
  • 4
    I believe it's because there's an implicit conversion from `DateTime` to `DateTime?`. However, this conversion isn't checked consistently... – Jon Skeet Apr 23 '15 at 12:02
  • (Or at least wasn't checked consistently... I'm sure there used to be some oddities around it, but I can't reproduce them with Roslyn.) – Jon Skeet Apr 23 '15 at 12:03

1 Answers1

7

Although time is of a non-nullable value type, it can be converted to nullable and compared to null. The comparison would yield false, which is a valid outcome.

This does not mean, however, that it is a good code. Tools, such as re:sharper, would flag this line with a warning saying "Expression is always false".

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Visual Studio 2013 displays a warning for some, but not all value types. For example, if you had used `int` instead of `DateTime`, you'd get a green squiggly line (warning) "expression is always false"; with `DateTime` you don't get such a warning. – stakx - no longer contributing Apr 23 '15 at 12:05