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.
More Related Contents:
- Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]
- Conditional operator assignment with Nullable types?
- .NET – Convert Generic Collection to DataTable
- Why is this code invalid in C#?
- In C# why can’t a conditional operator implicitly cast to a nullable type
- Type result with conditional operator in C#
- Correct way to check if a type is Nullable [duplicate]
- Why doesn’t the conditional operator correctly allow the use of “null” for assignment to nullable types? [duplicate]
- KeyValuePair with generic values [closed]
- Is there a constraint that restricts my generic method to numeric types?
- How do I clone a generic list in C#?
- Remove duplicates from a List in C#
- How to dynamically create generic C# object using reflection? [duplicate]
- Generic TryParse
- Making a generic property
- foreach vs someList.ForEach(){}
- Calling a static method on a generic type parameter
- No type inference with generic extension method
- How do I make the return type of a method generic?
- How to solve Operator ‘!=’ cannot be applied to operands of type ‘T’ and ‘T’ [duplicate]
- explicitly cast generic type parameters to any interface
- Specifying generic collection type param at runtime [duplicate]
- C# Generic Type Inference With Multiple Types
- Declare a generic type instance dynamically [duplicate]
- Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?
- Is the conditional operator slow?
- Checking type parameter of a generic method in C#
- How to make correct clone of the List? [duplicate]
- Get derived class type from a base’s class static method
- How to use Activator to create an instance of a generic Type and casting it back to that type?