Reputation: 47945
This is my code:
DateTime? test;
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null));
Why can I not set that variable to null
?
Upvotes: 1
Views: 118
Reputation: 218847
Aside from anything to do with Nullable<T>
(in this case, DateTime?
), the error is happening specifically here:
((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null))
Note that there's no mention of a nullable DateTime
in this code. And before the result of this code is assigned to a nullable DateTime
, this code by itself needs to be evaluated. It can't be, because of the error you're seeing.
The operator being used (: ?
) needs to be able to infer types from all arguments to the operation, and those types need to be able to match. Here you're passing it a DateTime
and null
which can't be matched. Try casting one of the arguments:
((objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday : null))
Upvotes: 3
Reputation: 13381
You can't set null in this case because ternary operator must return values same types try this:
test = (objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday): null;
Upvotes: 1
Reputation: 3171
Try with
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday): null;
Explanation: the structure of a ternary operator is:
variable = (condition)?(value if yes):(value if no);
Upvotes: 0