Handle DBNull in C#
Is there a better/cleaner way to do this?
int stockvalue = 0;
if (!Convert.IsDBNull(reader["StockValue"]))
stockvalue = (int)reader["StockValue"];
The shortest (IMHO) is:
int stockvalue = (reader["StockValue"] as int?) ?? 0;
Explanation:
- If reader["StockValue"] is of type int, the value will be returned, and the "??" operator will return the result
- If reader["StockValue"] is NOT of type int (e.g. DBNull), null will be returned, and the "??" operator will return the value 0 (zero).
The way I handle this is
int? stockvalue = reader["StockValue"] as int?;
Very simple, clean and one line. If for some reason I absolutely can't have a null value (which I find poor reasoning for usually since I'd rather know if a value has meaning or if it was unitialized for a primitive type) I would do:
int stockvalue = (reader["StockValue"] as int?).GetValueOrDefault(-1);