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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With