Brian Webster
Brian Webster

Reputation: 30855

.NET inline IF ternary operator returns unexpected decimal value

I expect the following to result in the value of 14D being placed in the variable D3.

However, this is not happening.

Dim D1 As Decimal = 14D
Dim D2 As Decimal = Nothing
Dim D3 As Decimal

D3 = If(D2 = Nothing, D1, D2)


The final value of D3 is 0D.


Why does D3 end up with the value of 0D rather than 14D?

UPDATE #1

Upvotes: 0

Views: 443

Answers (4)

mikesigs
mikesigs

Reputation: 11380

Decimal is a value type and can't actually be equal to Nothing. Setting a value type to Nothing will result in it taking it's default value (in this case 0D).

Here's a working solution:

Dim D1 As Decimal = 14D
Dim D2 As Decimal = Nothing
Dim D3 As Decimal

D3 = If(D2 = CType(Nothing, Decimal), D1, D2)

This is much cleaner in C#:

decimal d1 = 14m;
decimal d2 = default(decimal);
decimal d3;

d3 = (d2 == default(decimal)) ? d1 : d2;

Upvotes: 2

ilans
ilans

Reputation: 2707

Your code works as it is.

But usually I would use IsNothing(D2) and not D2 = Nothing.

Upvotes: 0

xpda
xpda

Reputation: 15813

Option 1 (most likely)

Make sure that you are examining the value of D3 in both the debugger AND in the actual application. For example, try this:

Response.Write(D3.ToString())

Does it output 0 or 14? I bet it outputs 0.

Sometimes the debugger shows false information.

Option 2

If you compile to x86 instead of x64, it will work just fine. Or, you can use If D2 = Nothing Then D3 = D1 Else D3 = D2. In fact, D3 = If(True, D1, D2) fails. It fails even if D2 is not assigned nothing. If D2 is assigned 1D, D3 is still assigned 0D. Must be a compiler error.

Upvotes: 1

ps2goat
ps2goat

Reputation: 8475

Decimal, just like other numeric value types (not reference types, like objects/classes are) default to 0. They cannot have Nothing assigned to them, as value types exist once declared.

If you want to set a value type to nothing, you must declare it as Nullable in one of the following ways:

Dim d1 As Nullable(Of Decimal) = Nothing

Or

Dim d2 As Decimal? = Nothing

The question mark is short-hand for the first example.

Upvotes: 0

Related Questions