Tutorial :Based on what precedence rules is a[x].SomeMember evaluated as (a[x]).SomeMember and not…?



Question:

a) Both dot operator ( a.x ) and index operator ( a[x] ) have the same level of precedence. So based on what precedence rules is an expression a[x].SomeMember evaluated as (a[x]).SomeMember and not as (a.SomeMember )[x]?

b) Is casting operator an unary operator ( and thus has lower precedence than dot operator ) and for that reason is an expression (int)a.xevaluated as (int)(a.x)?

thank you


Solution:1

For a)

From C# Specification, section 7.2.1:

When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed:

  • Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.
  • The assignment operators and the conditional operator (?:) are right-associative, meaning that operations are performed from right to left. For example, x = y = z is evaluated as x = (y = z).

This means that the operators will get precedence, in this situation, from left to right.

b) Yes, this is correct. This is a Cast Expression, described in section 7.6.6, which is applied to a unary expression, and casts are categorized with the Unary operators (Section 7.6) and treated with the same precedence.


Solution:2

a) The precedence is a left-to-right precedence. In evaluating the references, the compiler proceeds left to right in determining which equal operators receive precedence. Since a[x] precedes [x].SomeMember it gets referenced first.

b) It is not a unary operator but it has the same precedence as a unary.

Precedence of the C# Operators


Solution:3

a) Based on the sequence of code. a = b is interpreted differently to b = a for the same reason!

b) Casting is an unary operator as described here. Its specific behaviour is explained here.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »