ternary condition and nullable types [duplicate]
开发者_Python百科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"]);
}
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.
精彩评论