Handle DBNull in C#

前端 未结 13 662
梦谈多话
梦谈多话 2020-11-30 01:36

Is there a better/cleaner way to do this?

int stockvalue = 0;
if (!Convert.IsDBNull(reader[\"StockValue\"]))
    stockvalue = (int)reader[\"StockValue\"];


        
相关标签:
13条回答
  • 2020-11-30 02:37

    Not really. You could encapsulate it in a method:

    public int getDBIntValue(object value, int defaultValue) {
      if (!Convert.IsDBNull(value)) {
        return (int)value;
      }
      else {
        return defaultValue;
      }
    

    And call it like this:

    stockVaue = getDBIntVaue(reader["StockValue"], 0);
    

    Or you could use coalesce in your query to force the returned value to be non-null.

    Edit - corrected dumb code errors based on comments received.

    0 讨论(0)
提交回复
热议问题