开发者

Why this Conditional operator error? [duplicate]

This question already has answers here: Closed 11 years ago.

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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜