According to the documentation?: (Ternary operator) is right associative, i.e. is it done like this a? b: (c? d: e)

https://docs.microsoft.com/ru-ru/dotnet/csharp/language-reference/operators/conditional-operator

Why does this code show the operation of a ternary operator as a left associative? Those. the call to the property Cnt should have happened exactly 2 times (with x == 3), and as a result we get only one call.

static class Counter { public static int cnt; public static int Cnt { get { cnt++; return cnt; } } } public static void Main() { int someValue = 128; int x = int.Parse(Console.ReadLine()); var tmp = (x == 3) ? Counter.Cnt : (x == 3) ? Counter.Cnt : someValue; // Выполнение справа-налево Console.WriteLine(tmp + " cnt = " + Counter.cnt); // Обратите внимание, что здесь обращение напрямую к полю класса } 
  • And I, too, for council 1, the ternary operator is conditional, but you are not in a condition, but put Cnt in the response branch while Cnt condition either [1] or [2], respectively, the call occurs once. - nick_n_a

1 answer 1

Because there is a calculation of only one of the operands - the one that is returned depending on the condition.

Bold for x == 3 :

(x == 3)? Counter.Cnt : ((x == 3)? Counter.Cnt: someValue);

Bold for x != 3 :

(x == 3)? Counter.Cnt: ((x == 3)? Counter.Cnt: someValue );

  • (x == 3)? Counter.Cnt: ((x == 3)? Counter.Cnt: someValue); First, because the ternary operator in parentheses, and then external, right associative, right? - wolframrus
  • one
    @wolframrus from your own link Если параметр condition имеет значение true, вычисляется выражение first_expression и итог этого вычисления становится результатом. Если параметр condition имеет значение false, вычисляется выражение second_expression и итог этого вычисления становится результатом. Если параметр condition имеет значение true, вычисляется выражение first_expression и итог этого вычисления становится результатом. Если параметр condition имеет значение false, вычисляется выражение second_expression и итог этого вычисления становится результатом. - tym32167 2:07 pm
  • @wolframrus now determine what will be calculated in your expression and what will not be - tym32167