Why this Conditional operator error? [duplicate]
Possible Duplicate:
Conditional operator assignment with Nullable<value> 开发者_运维问答types?
Hi, Why this doesn't work?
DateTime? SomeNullableDateTime = string.IsNullOrEmpty("") ? null : Convert.ToDateTime("01/02/1982");
Is it an error somewhere? The problem seems to be the null because
DateTime? SomeNullableDateTime = string.IsNullOrEmpty("") ? Convert.ToDateTime("01/02/1982") : Convert.ToDateTime("01/02/1982");
Works fine..
Thanks
Both conditional values need to be of the same type or allow implicit conversion from one type to another, like so:
DateTime? SomeNullableDateTime = string.IsNullOrEmpty("") ? (DateTime?)null : Convert.ToDateTime("01/02/1982");
More information can be found here, but to summarize:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
Because null
and Convert.ToDateTime
are not the same type.
You can use this:
DateTime? SomeNullableDateTime = string.IsNullOrEmpty("") ? (DateTime?)null : new DateTime?(Convert.ToDateTime("01/02/1982"));
精彩评论