views:

1085

answers:

4

Could someone explain why this works in C#.NET 2.0:

 Nullable<DateTime> foo;
 if (true)
  foo = null;
 else
  foo = new DateTime(0);

...but this doesn't:

  Nullable<DateTime> foo;
 foo = true ? null : new DateTime(0);

The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."

Not that I can't use the former, but the second style is more consistent with the rest of my code.

+20  A: 

This question has been asked a bunch of times already. The compiler is telling you that it doesn't know how convert null into a DateTime.

The solution is simple:

DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);

Note that Nullable<DateTime> can be written DateTime? which will save you a bunch of typing.

Stewart Johnson
Yeah, what he said.
MojoFilter
Perfect, that works, thanks!
Nick Gotch
+3  A: 

It's because in a ternary operator, the two values must be the same type.

MojoFilter
A: 

Check John Skeets answer here for a good explanation (no credit taken)

DilbertDave
+7  A: 

FYI (Offtopic, but nifty and related to nullable types) we have a handy operator just for nullable types called the null coalescing operator

??

Used like this:

// Left hand is the nullable type, righthand is default if the type is null.
Nullable<DateTime> foo;
DateTime value = foo ?? new DateTime(0);
FlySwat
How does this answer his question??
Stewart Johnson
Nick is trying to assign null to foo if some condition is true. The null coalesce will assign DateTime(0) to value if foo is null. The two are completely unrelated.
Jeromy Irvine
Hence the FYI, offtopic but a nice thing to know.
FlySwat
Ah, OK. It is pretty useful to know.
Jeromy Irvine