0

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

Community
  • 1
  • 1
bAN
  • 13,375
  • 16
  • 60
  • 93

2 Answers2

2

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.

CodeNaked
  • 40,753
  • 6
  • 122
  • 148
0

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"));
Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144