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.GetDecimal(7);
This is the error message I am getting:
Cannot implicitly convert type 'decimal?' to 'decimal'. An explicit conversion exists (are you missing a cast?)
Where am I going wrong, please someone tell me.
decimal?
indicates that it's a nullable decimal; you have to use theValue
property to get the actual value (if it exists, determined viaHasValue
).I'm assuming
curPrice
is a non-nullable decimal, in which case you need to also figure out a better value to return thannull
from the true side of your ternary operator.either convert
curPrice
to nullable, or use .Value property of nullable types.If
curPrice
is a property of a class thenSince the left side (
Price
) does not allow fornull
then you cannot set its value to something that could benull
. Therefore, use.GetValueOrDefault(decimal defaultValue)
to return a default value whennull
.How about converting the
decmial?
type todecimal
?You have to have what value you like
inrec.curPrice
to have whensdr.GetDecmial(7)
is null.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);
?