Pregunta

I have the following code that seems to work:

DataRow row = <result of a query>;
string strVarName = (row["VarName"]??"").ToString();

I can also use something like this - and it also works:

string strVarName = row["VarName"]==null ? "" : row["VarName"].ToString();

I would like to use the same form to get a date. Intellisense informs me that the nullable operator does not like working with dates, so I am trying something similar, I have to make

string strVarName = row["VarName"]==DBnull.Value ? "" : row["VarName"].ToShortDateString();

Get that? For strings I compare to null, but for dates I compare to DBnull. The date string will not work consistently with a comparison to null. I'm okay with this ... and it may be that the string comparison would work if I tried to compare it to DBNull.Value . I'm just curious why it seems I must use DBNull.Value when comparing to a DateTime field of a DataRow, whereas I may use null when comparing to a string field.

¿Fue útil?

Solución

DateTime is a value type and can not be null, hence you can't compare it to null (just like you can't compare int to null).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top