How to safely cast nullable result from sqlreader to int?

Burjua picture Burjua · Feb 21, 2012 · Viewed 17.6k times · Source

I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.

I'm doing it in this way at the moment:

...
reader = command.ExecuteReader();
while (reader.Read()) {
     int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
     ...
}
...

but getting a Object cannot be cast from DBNull to other types. when PublicationYear is null.

How can I get the value safely?

Thanks.

Answer

Mr Lister picture Mr Lister · Feb 21, 2012

You should compare reader["PublicationYear"] to DBNull.Value, not null.