C# Operator Precedence & Associativity
In C#, operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. Operator associativity determines the order in which operators of the same precedence are evaluated.
Here is a table of C# operators sorted by precedence, from highest to lowest:
Precedence | Operator | Associativity |
---|---|---|
1 | () | Left to right |
2 | ++ -- (postfix) | Left to right |
+ - ! ~ | ||
(type) cast | ||
* / % | ||
3 | ++ -- (prefix) | Right to left |
+ - (unary) | ||
& | ||
sizeof | ||
new | ||
typeof | ||
4 | == != | Left to right |
5 | & | Left to right |
6 | ^ | Left to right |
7 | | | Left to right |
8 | && | Left to right |
9 | || | Left to right |
10 | ?: | Right to left |
11 | = += -= *= /= %= &= | Right to left |
^= |= <<= >>= | ||
12 | throw | Right to left |
As you can see from the table, operators with higher precedence are evaluated before operators with lower precedence. For example, in the expression 3 + 4 * 5
, the multiplication operator *
has higher precedence than the addition operator +
, so it is evaluated first, and the result is 23
.
Operator associativity determines the order in which operators of the same precedence are evaluated. For example, the addition and subtraction operators have the same precedence, so in the expression 10 - 5 + 2
, they are evaluated from left to right, resulting in a value of 7
.
You can use parentheses to override operator precedence and force the evaluation order you want. For example, in the expression (3 + 4) * 5
, the parentheses force the addition to be evaluated first, resulting in a value of 35
.
It's important to be aware of operator precedence and associativity when writing complex expressions to ensure that they are evaluated correctly.