Search code examples
c#sqldatareaderdbnull

Using GetDecimal gives an error in condition expression


Hi I am using GetDecimal() but it gives an error in condition expression.

Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)

As this gives an error saying "Type of conditional expression cannot be determined because there is no implicit conversion between string and decimal ". What can be used as default value for GetDecimal()? Any help?


Solution

  • The problem here is this part:

    Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)
                                ^-+^   ^----------+-------^
                                  |               |
                                  |               +-- Decimal type
                                  +-- not a Decimal type
    

    The expression fails to compile because the compiler is not able to deduce that in order to make it work, it would have to make the last part a nullable Decimal, thus it tries to find a type that can hold null, lands on string, and thus the error message.

    You need to specify that you want a nullable decimal as the result, assuming Data is also nullable decimal.

    If it is, this will work:

    Data = varCmd.IsDBNull(2) ? (Decimal?)null : varCmd.GetDecimal(2)
    

    If it isn't, then you need to decide what to store into Data if the column is null (DBNull), probably 0:

    Data = varCmd.IsDBNull(2) ? 0 : varCmd.GetDecimal(2)