Nullable type issue with ?: Conditional Operator
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);
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.