Elad Benda Elad Benda - 7 days ago 5
SQL Question

casting datareader value to a to a Nullable variable

I'm trying to run the following code but get a casting error.
How can I rewrite my code to achive the same ?

boolResult= (bool?)dataReader["BOOL_FLAG"] ?? true;
intResult= (int?)dataReader["INT_VALUE"] ?? 0;


Thanks

Answer

Use the "IsDbNull" method on the data reader... for example:

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? null : (bool)dataReader["Bool_Flag"]

Edit

You'd need to do something akin to: bool? nullBoolean = null;

you'd have

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? nullBoolean : (bool)dataReader["Bool_Flag"]