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.
Or, alternatively:
DBNull
is not the same asnull
. You should try something like this instead:as an alternative you can do the following. as you are converting DBNull to 0, alter the procedure that does the select. so that the select itself returns zero for a null value.
snippet to demonstrate the idea
advantage of this is that, no additional checking is needed in your code.
Change your test from
(reader["PublicationYear"] != null)
to(reader["PublicationYear"] != DBNull.Value)
.Change
reader["PublicationYear"] != null
to
reader["PublicationYear"] != DBNull.Value
You should explicitly check if the value returned is of type
DBNull
In fact, you can do this comparison by value as well as type:
In short - you can expect
DBNull
to be returned for nulls from the database, rather than null itself.