Cannot implicitly convert to decimal? to "decimal".

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

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

This is the error message I get:

Cannot implicitly convert to decimal? to "decimal". An explicit conversion exists (do you miss the role?)

Where am I wrong, please tell me someone.

+6
source share
4 answers

either convert curPrice to nullable, or use the .Value property of types with NULL capability.

If curPrice is a class property, then

 public decimal? curPrice { get; set; } 
+10
source

decimal? indicates that this is a nullable decimal value ; you must use the Value property to get the actual value (if it exists, it is determined through HasValue ).

I assume curPrice is a non-zero number, in which case you also need to find a better return value than null from the true side of your ternary operator.

+19
source
 inrec.curPrice = sdr.GetValueOrDefault(0m) 

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

+4
source

How to convert decmial? type decmial? in decimal ?

You should have what you like inrec.curPrice if sdr.GetDecmial(7) is null.

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

I suggested that you want to use 0 if the return value is null. If you do not change 0M to some other decimal value.

--- Update after retry

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

+3
source

Source: https://habr.com/ru/post/915329/


All Articles