Reputation: 13545
What prints this program?
static void Main(string[] args)
{
int? other = null;
int value = 100 + other ?? 0;
Console.WriteLine(value);
}
I know I just do not have the language specs in my head. But still it is surprising that it prints 0 instead of 100. Is there a reasonable explanation for this strange behavior?
When I use braces then I get the right result.
static void Main(string[] args)
{
int? other = null;
int value = 100 + (other ?? 0);
Console.WriteLine(value);
}
Upvotes: 4
Views: 88
Reputation: 172618
You are getting the result as 0 because of plus(+)
operator having higher precedence over Null Coalescing Operator
??
. So your expression is evaluated as:
(100 + other) ?? 0;
which returns 0.
In your second case you are evaluating the expression (other ?? 0) first giving it the higher precedence. And hence you get the correct or the expected result.
Upvotes: 5
Reputation: 35746
The precedence of C# operators is defined clearly here.
We can see,
x + y – addition.
is 29th, and,
x ?? y – returns x if it is non-null; otherwise, returns y.
is 46th, so Additive Addition is evaluated before Null Coalescence.
Speculation of the reasoning behind this is off-topic for this site and a much deeper question. Answers here will likely be subjective, even with direct input from the technical group, and a complete answer will be longer than a few paragraphs.
Upvotes: 2
Reputation: 9593
Currently the expression evaluates as:
(100 + other) ?? 0;
The value of other
is null and a number plus null is still null. So the expression outputs 0.
In your second example, you are evaluating the null check first, then adding 100.
Upvotes: 5