C# Operator Precedence

In my previous blog post on the difference between i++ and ++i, I made a comment that i++ had a higher precedence than ++i. In C#, operators are grouped into categories and each category has a precedence. Categories with a higher precedence will execute prior to categories with a lower precedence. In the case of i++ and ++i, the Postfix increment operator is in the Primary operator category and the Prefix increment operator is in the Unary category.

In total, C# has 15 operator categories (listed in descending order of precedence):

When there are two operators with the same precedence, the associativity of the operators determines the order or operations. Except for assignment operators, all binary operators are performed left to right. For example, the operation i + j + k is evaluated as (i + j) + k. The expression x OR y OR z is evaluated as (x OR y) OR z.

For the assignment operators and the conditional operator the operations are performed right to left. The statement x = y + z is evaluated as x = (y + z), and the statement x = y = z is evaluated as x = (y = z).

To control precedence and associativity, you can use parentheses. The statement x = 1 + 2 * 3 will default to x = 1 + (2 * 3), but you can force the addition operator to run first by using parentheses to create x = (1 + 2) * 3.