Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable With Surprising Result

Tags:

c#

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);
}
like image 510
Alois Kraus Avatar asked Dec 15 '22 10:12

Alois Kraus


1 Answers

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.

like image 100
Steve Avatar answered Dec 17 '22 02:12

Steve