0

Possible Duplicate:
Why is this code invalid in C#?

Could you please analyze CS1 and CS2. Why should I need to add (DateTime?)null in CS1 while I use _my_date = null; in CS2. If I do not add (DateTime?) in CS1, I will be 'blessed' :( by the following error Type of conditional expression cannot be determined because there is no....

 DateTime? _my_date; DataTable _dt = GetData(); // Code Snippet 1: CS1 _my_date = _dt.Rows[0]["MyDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(_dt.Rows[0]["MyDate"]); // Code Snippet 2: CS2 if (_dt.Rows[0]["MyDate"] == DBNull.Value) { _my_date = null; } else { _my_date = Convert.ToDateTime(_dt.Rows[0]["MyDate"]); } 
2
  • What do you mean by cs1 and cs2? is that by any means c# 1.1 and c# 2.0? Commented Jul 28, 2011 at 14:03
  • @NoProblemBase: If you read the example code, CS1 and CS2 are in the comments... Commented Jul 28, 2011 at 14:04

1 Answer 1

0

Because the type of 'null' can not be determined. I imagine it's something to do with the size of types. Say for example that null, means all the bits will be set to 0 (I'm speculating here), then you need to know how many bits are in your structure. A short for example has less bytes than a DateTime.

So in this case you need to inform it as to the type it's expecting because it can't convert null, to the nullable datetime.

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't quite right. It's not a size thing, it's that null is typeless, and the second type isn't a nullable DateTime (just a regular one.) If it was, this actually would compile. The issue is that the compiler refuses to guess as to what type which is "bigger" than both sides it should choose here (since multiple types could be appropriate.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.