Search code examples
c#dbnull

Casting a NULL value


I'm trying to populate a class object with values from a database table. The someObject.Property field is a nullable int type.

someObject.Property = Convert.ToInt32(dbReader["SomeField"]);

So, if SomeField is null, Convert will give a DBNull error. Is there a specific method I should be using for this?


Solution

  • This should work...

    someObject.Property = dbReader["SomeField"].Equals(DBNull.Value)
        ? null
        : (Int32)dbReader["SomeField"];
    

    @John - Good catch. Edit to reflect that oversight.