Cannot implicitly convert type 'decimal?' to 'decimal'.

前端 未结 4 904
南笙
南笙 2021-01-04 10:08

sdr is my sqldatareader and I want to check that the curPrice value which is of type decimal is null.

inrec.curPrice = sdr.IsDBNull(7) ? (decimal?)null : sdr.

相关标签:
4条回答
  • 2021-01-04 10:57
    inrec.curPrice = sdr.GetValueOrDefault(0m)
    

    Since the left side (Price) does not allow for null then you cannot set its value to something that could be null. Therefore, use .GetValueOrDefault(decimal defaultValue) to return a default value when null.

    0 讨论(0)
  • 2021-01-04 11:02

    decimal? indicates that it's a nullable decimal; you have to use the Value property to get the actual value (if it exists, determined via HasValue).

    I'm assuming curPrice is a non-nullable decimal, in which case you need to also figure out a better value to return than null from the true side of your ternary operator.

    0 讨论(0)
  • 2021-01-04 11:04

    either convert curPrice to nullable, or use .Value property of nullable types.

    If curPrice is a property of a class then

    public decimal? curPrice
    {
       get;
       set;
    }
    
    0 讨论(0)
  • 2021-01-04 11:06

    How about converting the decmial? type to decimal ?

    You have to have what value you like inrec.curPrice to have when sdr.GetDecmial(7) is null.

    inrec.curPrice = sdr.GetDecimal(7) ?? 0M;
    

    I assumed that you would want to use 0 if what's returned was null. If not change 0M to some other decimal value.

    --- Update after replay

    How about inrec.curPrice = sdr.IsDBNull(7) ? 0M : sdr.GetDecimal(7); ?

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