new to C# so I’m having an issue with a short-hand statement. I want to convert…
if (m_dtLastLogin == null)
drow["LastLogin"] = DBNull.Value;
else
drow["LastLogin"] = m_dtLastLogin;
to
drow["LastLogin"] = (m_dtLastLogin == null) ? System.DBNull.Value : m_dtLastLogin;
The long-hand version works great, however, the short-hand version generates the error “Type of conditional cannot be determined because there is no implicit conversion between ‘System.DBNull’ and ‘System.DateTime?'”. My supporting code is basically…
private DateTime? m_dtLastLogin;
m_dtLastLogin = null;
DataRow drow;
drow = m_oDS.Tables["Users"].Rows[0];
Can someone help me with the short-hand here?
Well, the error message is pretty clear. The compiler needs to determine the type of the whole x?y:z expression. If y and z have the same type, it’s easy. If y is convertible to z, the type of the expression is that of z, likewise if z is convertible to y the type is that of y.
In your case the type of y is DBNull, the type of y is the type of m_dtLastLogin (probably a datetime). Those two types cannot be converted into each other and have no common base type (except for Object), so the compiler doesn’t know what to do.
You can help the compiler, however, by casting either y or z to object:
or
This way the whole expression has the type object, which can then be assigned to
drow["LastLogin"].Reference:
C# language specification – http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
Section 14.13, Conditional operator
Quote