tags:

views:

44

answers:

3

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

+1  A: 

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

Joel Etherton
+1  A: 

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.

CesarGon
+1  A: 

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.

Reed Copsey
For some reason I didn’t think that dot and index operators also have left associativity
AspOnMyNet
Why isn’t casting considered an unary operator? After all, it has only one operand?
AspOnMyNet
Well, it's an expression acted upon a unary expression. The C# spec treats it as a unary operator. I reworded - since the C# spec treats it as unary.
Reed Copsey
thank you all for your help
AspOnMyNet