C # operator coalesce

Why does the following code return false?

public static void Main()
{
    bool? someCondition = true;
    bool someConditionOverride = false;


    bool? result = someCondition ?? someConditionOverride ? false : (bool?)null;

    Console.WriteLine(result);
}

I calculated the result will be true, since someConditionnot null, but the ??operator will return true. However, it seems that the right operand is evaluated first, and the left side is simply ignored.

Adding parentheses eliminates the confusion:

bool? result = someCondition ?? (someConditionOverride ? false : (bool?)null)

And the result will be true. However, I am still wondering why in the first example the left side of the left side was ignored.

+4
source share
1 answer

"the left side is simply ignored"? How much do you think is possible?

Operator priority indicates that your first version is parsed as follows:

bool? result = (someCondition ?? someConditionOverride) 
                   ? false 
                   : (bool?)null;

someCondition , . true:

(someCondition ?? someConditionOverride) 

, ?, false, .

, , . , ; . # .

, . . , ( , , - , ).

:. : Eric , a + b * c, , , , , , , .

+17

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


All Articles