- Chapter 3: Writing C# Expressions
- Binary Operators
- The Ternary Operator
- Other Operators
- Enumeration Expressions
- Array Expressions
- Statements
- Blocks
- Labels
- Declarations
- Operator Precedence and Associativity
- Summary
Operator Precedence and Associativity
When evaluating C# expressions, there are certain rules to ensure the outcome of the evaluation. These rules are governed by precedence and associativity and preserve the semantics of all C# expressions. Precedence refers to the order in which operations should be evaluated. Sub-expressions with higher operator precedence are evaluated first.
There are two types of associativity: left and right. Operators with left associativity are evaluated from left to right. When an operator has right associativity, its expression is evaluated from right to left. For example, the assignment operator is right associative. Therefore, the expression to its right is evaluated before the assignment operation is invoked. Table 3.3 shows the C# operators, their precedence, and associativity.
Certain operators have precedence over others to guarantee the certainty and integrity of computations. One effective rule of thumb when using most operators is to remember their algebraic precedence. Here's an example:
int result; result = 5 + 3 * 9; // result = 32
This computes 3 * 9 = 27 + 5 = 32. To alter the order of operations use parentheses, which have a higher precedence:
result = (5 + 3) * 9; // result = 72
This time, 5 and 3 were added to get 8 and then multiplied by 9 to get 72. See Table 3.3 for a listing of operator precedence and associativity. Operators in top rows have precedence over operators in lower rows. Operators on the left in each row have higher precedence over operators to the right in the same row.
Table 3.3 Operator Precedence and Associativity
Operators |
Associativity |
---|---|
(x), x.y, f(x), a[x], x++, x--, new, typeof, sizeof, checked, unchecked |
Left |
+ (unary), - (unary), ~, ++x, --x, (T)x |
Left |
*, / % |
Left |
+ (arithmetic), - (arithmetic) |
Left |
<<, >> |
Left |
<, >, <=, >=, is, as |
Left |
==, != |
Left |
& |
Left |
^ |
Left |
| |
Left |
&& |
Left |
|| |
Left |
?: |
Right |
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= |
Right |