Reputation: 459
In c# (nullable types)
int a = 10;
int? b = 20;
int? c = null;
System.Console.WriteLine( a+c??b );
Output is : 20
if (c??b +a) then Output is 30
I don't understand why ..
Upvotes: 1
Views: 450
Reputation: 21752
c??b + a is evaluated as
c?? (b+a)
or slightly expanded
c == null ? b + a : c
or if we substitute with the actual values
null == null ? 20 + 10 : null)
whereas a +c??b is evaluated as
(a+c)??b
or if we expand slightly
(a + c) == null ? b : c+a
or if we substitute with the actual values
(10 + null) == null ? 20 : 10 + null
which again can be shortened to
null == null ? 20 : null
the addition operator for nullable types always return null if at least one of the operands are null
Upvotes: 1
Reputation: 2099
Check here: ECMA-334: 14.2.1 Operator precedence and associativity
The order of precedence of Null Coalescing operator (??) is very less than that of '+'. So, '+' is always evaluated first.
In your case,
int a = 10;
int? b = 20;
int? c = null;
a+c??b evaluates as (a+c)??b = (10+null)??20 = null??20 = 20
c??b+a evaluates as c??(b+a) = null??(10+20) = (10+20) = 30
Upvotes: 1
Reputation: 1502826
It's just a matter of precedence.
This:
System.Console.WriteLine(a + c ?? b);
is equivalent to:
System.Console.WriteLine((a + c) ?? b);
a + c
is null (because c
is null), therefore 20 is printed (the value of b
)
Whereas this:
System.Console.WriteLine(c ?? b + a);
is equivalent to:
System.Console.WriteLine(c ?? (b + a));
c
is null, therefore the RHS (b + a
) is evaluated, and that's 30.
Upvotes: 2
Reputation: 7489
The ??
operator is used to check for nulls. It returns either the value in question, or a fallback if it is null.
c ?? b
means "c, unless c is null, in which case b".
c ?? b + a
checks c, and sees that it is null, and uses b (20) instead. It then adds a (10) to get 30.*
a + c ?? b
seems to be applying the ??
to a + c
rather than just to c, resulting in the whole thing being replaced with b (20).
*Not sure about order of operations in this case, it might be using (b + a) due to c being null.
Upvotes: 0
Reputation: 564741
When you write:
System.Console.WriteLine( a+c??b );
It will effectively evaluate as:
int? temp = a + c;
System.Console.WriteLine(temp ?? b);
The "temp" above is null, so you get the result of b
.
Upvotes: 1
Reputation: 15577
Since c is null then the answer is b! That's what your double ? do.
Upvotes: 0