Unsuccessful with amazing result

What prints this program?

static void Main(string[] args)
{
    int? other = null;
    int value = 100 + other ?? 0;
    Console.WriteLine(value);
}

I know that I just don't have the language specifications in my head. But it is still surprising that it prints 0 instead of 100. Is there any reasonable explanation for this strange behavior?

When I use curly braces, I get the correct result.

static void Main(string[] args)
{
    int? other = null;
    int value = 100 + (other ?? 0);
    Console.WriteLine(value);
}
+4
source share
3 answers

The priority of C # operators is defined here .

We can see,

x + y is the complement.

equal to 29, and

x ?? y - returns x if it is not equal to zero; otherwise returns y.

- 46, so additive addition is rated to Null Coalescence.

- . , , , .

+2

:

(100 + other) ?? 0;

other null, null null. , 0.

, 100.

+5

0 - plus(+) Null Coalescing Operator ??. , :

(100 + other) ?? 0;

0.

(? 0), . , , .

+5
source

Source: https://habr.com/ru/post/1615194/


All Articles