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"]);
        }
Community
  • 1
  • 1
Rauf
  • 12,326
  • 20
  • 77
  • 126

1 Answers1

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.

Ian
  • 33,605
  • 26
  • 118
  • 198
  • 1
    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.) – dlev Jul 28 '11 at 14:05