Cannot implicitly convert type 'decimal?' to 'decimal'.
Asked Answered
S

4

13

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.

Speedway answered 9/5, 2012 at 20:50 Comment(0)
P
13

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;
}
Ptolemaeus answered 9/5, 2012 at 21:0 Comment(0)
T
31

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.

Tailspin answered 9/5, 2012 at 20:52 Comment(1)
I'm confused. Would you happen to have code samples to explain what you mean..real sorry this is very new to me.Speedway
P
13

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;
}
Ptolemaeus answered 9/5, 2012 at 21:0 Comment(0)
B
6
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.

Bumble answered 29/9, 2016 at 18:58 Comment(0)
H
4

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); ?

Heelandtoe answered 9/5, 2012 at 21:2 Comment(2)
When I do that, I get this error: Error 7 Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'Speedway
Ah.. I just looked up .GetDecimal() in MDSN, It returns a decimal and not decimal? so my answer was nonsense. Sorry about that.Heelandtoe

© 2022 - 2024 — McMap. All rights reserved.