Search code examples
c#nullable

Specified cast is not valid - Decimal


I'm trying to declare a decimal number which will take the value of dr["index"] or the value null if dr["index"] is null.

Here is my line of code :

Decimal number = (Decimal)(dr["index"] ?? 0);

I got the following error :

System.Invalid.CastException : 'Specified cast is not valid' 

Would you know how to fix that problem ?


Solution

  • I'd go with in case of DBNull.Value:

    Convert.ToDecimal(dr["index"] == DBNull.Value ? 0m : dr["index"])
    

    or in case of null value:

    Convert.ToDecimal(dr["index"] ?? 0m)
    

    If dr[index] can only be a numeric value.