Domanda

I have the following code:

decimal? a = 2m;
decimal? b = 2m;
decimal c = a ?? 1m * b ?? 1m;

Since both a and b have been filled in, I'm expecting c to give me the result of 4.

However, the result I get is 2, in which case b is taken as 1 instead of 2.

Does anyone know what is the reason behind this behaviour?

È stato utile?

Soluzione

The expression works as:

decimal c = a ?? (1m * b) ?? 1m;

As a has a value, you get that.

Altri suggerimenti

group the value condition if you want to get the value of 4

decimal c = (a ?? 1m) * (b ?? 1m);

your current syntax is evaluated as

decimal c = a ?? (1m * b ?? 1m);

and the reason why you get the value of 2 (as for a)

decimal c = a ?? 1m * b ?? 1m;

Equals to:

if (a != null)
    c = a
else
    ...

In your case a is not null and has the value of 2 so this is the result.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top