Course Content
C# Tutorial
About Lesson

Operator precedence and associativity

Operator precedence in C# determines the order in which operators are evaluated when an expression contains multiple operators. It’s crucial to comprehend this concept to write efficient and error-free code.

What is Operator Precedence?

In C#, each operator has a specific precedence level, which determines the order in which operations are performed. Operators with higher precedence are evaluated first before those with lower precedence.

Common Operator Precedence Levels

  1. Parentheses () Parentheses have the highest precedence. Expressions within parentheses are evaluated first.

  2. Unary Operators (++x, –y, !) Unary operators come next, including increment (++), decrement (–), and logical negation (!).

  3. Multiplication and Division (*, /, %) Multiplication, division, and modulus operators are evaluated next.

  4. Addition and Subtraction (+, -) Addition and subtraction operators are evaluated after multiplication and division.

  5. Relational Operators (<, >, <=, >=) Relational operators, used for comparison, follow the arithmetic operators.

  6. Equality Operators (==, !=) These operators test for equality and inequality.

  7. Logical AND (&&) Logical AND operator combines two Boolean expressions.

  8. Logical OR (||) Logical OR operator combines two Boolean expressions.

  9. Assignment Operators (=, +=, -=) Assignment operators have the lowest precedence level.

Operator Associativity

When operators share the same precedence level, their associativity determines the order of evaluation. C# operators can be left-associative or right-associative.

  • Left-Associative Operators Left-associative operators are evaluated from left to right. For instance, arithmetic operators like addition and subtraction follow left-associativity.

  • Right-Associative Operators Right-associative operators are evaluated from right to left. However, C# does not contain right-associative operators by default.

Importance in Writing Code

Understanding operator precedence and associativity is critical for writing clear and unambiguous code. Misinterpreting precedence can lead to unexpected results or errors in calculations. Hence, it’s essential to use parentheses to explicitly define the order of operations when needed.