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.

user1270384
  • 711
  • 7
  • 24
  • 53

4 Answers4

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.

ravuya
  • 8,586
  • 4
  • 30
  • 33
  • 4
    I'm confused. Would you happen to have code samples to explain what you mean..real sorry this is very new to me. – user1270384 May 09 '12 at 21:32
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;
}
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
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.

Nissa
  • 4,636
  • 8
  • 29
  • 37
LazyDog
  • 317
  • 4
  • 5
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); ?

Shintaro Sasaki
  • 128
  • 1
  • 13
  • When I do that, I get this error: Error 7 Operator '??' cannot be applied to operands of type 'decimal' and 'decimal' – user1270384 May 09 '12 at 21:29
  • Ah.. I just looked up `.GetDecimal()` in MDSN, It returns a `decimal` and not `decimal?` so my answer was nonsense. Sorry about that. – Shintaro Sasaki May 09 '12 at 21:34