C# Operator Precedence (Order of Operations)

In C#, when multiple operators are used in a single expression, the order in which they are evaluated is determined by the operator precedence. Operator precedence determines which operators are evaluated first, second, and so on, and it is similar to the rules of arithmetic. Understanding operator precedence is important in C# programming, as it affects the output of expressions and can lead to unexpected results if not used properly.

Operator Precedence Rules

C# follows a set of rules to determine the order in which operators are evaluated. Here are the general rules:

  1. Operators in parentheses are evaluated first.
  2. Unary operators (such as ! or ++) are evaluated next.
  3. Multiplication, division, and modulus operators are evaluated next.
  4. Addition and subtraction operators are evaluated next.
  5. Comparison operators (such as < or >=) are evaluated next.
  6. Logical AND and OR operators are evaluated next.
  7. The assignment operator is evaluated last.

The following table shows the operator precedence in C#, with operators on the top being evaluated first:

PrecedenceOperatorDescription
1()Parentheses
2!, ++, --Unary operators
3*, /, %Multiplication, division, modulus
4+, -Addition, subtraction
5<, <=, >, >=Comparison operators
6&&Logical AND
7||Logical OR
8=, +=, -=, etc.Assignment operator (right-to-left associativity)

Note that some operators have left-to-right associativity (such as the multiplication operator *) and some have right-to-left associativity (such as the assignment operator =). Left-to-right associativity means that the operators are evaluated from left to right, while right-to-left associativity means that the operators are evaluated from right to left.

Examples

Let's take a look at some examples to see how operator precedence works in C#:

Example 1: Parentheses

In the following example, the expression inside the parentheses is evaluated first:

1int result = (10 + 5) * 2; 2// result = 30

Example 2: Unary Operators

In the following example, the unary operator (--) is evaluated first:

1int num1 = 5; 2int num2 = --num1 + 3; 3// num1 = 4, num2 = 7

Example 3: Multiplication and Division

In the following example, multiplication and division operators are evaluated before addition and subtraction:

1int result = 10 + 5 * 2 / 4; 2// result = 12

Example 4: Comparison Operators

In the following example, the comparison operator (>) is evaluated before the logical AND operator:

1int num1 = 5; 2int num2 = 10; 3bool result = num1 > 3 && num2 < 15; 4// result = true

Example 5: Assignment Operators

In the following example, the assignment operator is evaluated last:

1int num1 = 5; 2int num2 = 10; 3num2 += num1 * 2; 4// num2 = 20

Understanding operator precedence is important in C# programming, as it affects the output of expressions and can lead to