Monday, March 19, 2012

Datareader, DBNull and ? Operator

Hi!

I was trying to use the ?? operator with an DBDatareader. eg:

long lValue = Convert.ToInt32(objReader["ParentID"] ?? -1);

which throws the following exception:"... Object cannot be cast from DBNull to other types."
I think the reason is, that DBNull.Value isn′t actually null. Therefore I changed my code to:

long lValue = objReader["ParentID"] != DBNull.Value ? Convert.ToInt32(objReader["ParentID"]) : -1;

Is there a better way of doing this ? Can one use the ?? operator with a Datareader anyway?

Thanks for your help!

PS: sorry for my poor english.

Hi,

the ?? operator is used in conjunction with nullable types. The way you wrote it using the ?: operator is just fine.

Grz, Kris.

|||

Thanks a lot!