title: Why do I get an InvalidCastException when reading values from OdbcDataReader after checking for null values?
body: <p>Using OdbcDataReader in C#, I have a query that returns an integer column which could contain nulls.</p>
  
  <p>For each row, I want to test whether the value is null and handle it appropriately. However, when I do this using IsDBNull I get an InvalidCastException even for rows that are not null. Why does this occur?</p>
  
  <p>If I leave out the IsDBNull check, I get an error only for rows that contain nulls.</p>
  
  <pre><code>OdbcConnection DbConnection = new OdbcConnection("DSN=...");
  DbConnection.Open();
  OdbcCommand DbCommand = DbConnection.CreateCommand();
  DbCommand.CommandText = @"
                          select 1 as result from dual
                          union
                          select null as result from dual";
  OdbcDataReader DbReader = DbCommand.ExecuteReader();
  Int32 result;
  while (DbReader.Read())
  {
      if (!DbReader.IsDBNull(0))
      {
          result = DbReader.GetInt32(0);  // Results in InvalidCastException
      }
      else
      {
          result = 0;
      }
      Console.WriteLine(Convert.ToString(result));
  }
  
  Console.ReadLine();
  </code></pre>
  
  <p>Edit:</p>
  
  <p>The following technique to check for nulls seems to work. I would like to know why the above does not though.</p>
  
  <pre><code>object resultObject = DbReader.GetValue(0);
  if (resultObject != DBNull.Value)
  {
      result = Convert.ToInt32(resultObject);
  }
  else
  {
      result = 0;
  }
  </code></pre>