Handle DBNull in C#

前端 未结 13 753
梦谈多话
梦谈多话 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:20

    Yes you can use int? This way you can have a default value of null instead of 0. Since the result of stockvalue could potentially be 0 there isn't confusion as to whether the database was 0 or null. For instance like this (pre nullable) we had a default initialization of -1 to represent no value was assigned. Personally, I thought this was a little dangerous because if you forget to set it to -1, there is a data corruption issue that can be really difficult to track down.

    http://msdn.microsoft.com/en-us/library/2cf62fcy(VS.80).aspx

    int? stockvalue = null;
    
    if (!Convert.IsDBNull(reader["StockValue"]))
        stockvalue = (int)reader["StockValue"];
    
    //Then you can check 
    
    if(stockValue.HasValue)
    {
      // do something here.
    }
    

提交回复
热议问题