C# Operator Precedence
Operator Precedence
When a calculation has more than one operator, C# must decide which part to calculate first. This is called operator precedence.
It works like the math you know from school: multiplication and division are done before addition and subtraction.
Example
int result = 2 + 3 * 4;
Console.WriteLine(result); // 14
C# first calculates 3 * 4, which is 12. Then it calculates 2 + 12, which is 14.
Parentheses Come First
If you want the addition to happen first, put it inside parentheses ( ). C# always calculates the part inside parentheses first:
Example
int result = (2 + 3) * 4;
Console.WriteLine(result); // 20
Now C# first calculates 2 + 3, which is 5. Then it calculates 5 * 4, which is 20.
Left to Right
When operators have the same precedence, like + and -, or * and /, C# calculates from left to right:
Example
int result1 = 10 - 2 + 5; // (10 - 2) + 5 = 13
int result2 = 20 / 2 * 5; // (20 / 2) * 5 = 50
Console.WriteLine(result1);
Console.WriteLine(result2);
Order of Operations
The table below shows the most common operators. Operators at the top are calculated before operators further down:
| Order | Operator | Description |
|---|---|---|
| 1 | ( ) |
Parentheses |
| 2 | ++ -- ! |
Increment, decrement and logical not |
| 3 | * / % |
Multiplication, division and modulus |
| 4 | + - |
Addition and subtraction |
| 5 | < > <= >= |
Less than and greater than (or equal to) |
| 6 | == != |
Equal to and not equal |
| 7 | && |
Logical and |
| 8 | || |
Logical or |
| 9 | = += -= *= /= |
Assignment |
For example, + comes before >. So in the example below, C# first adds the numbers, and then compares the result:
Example
int points = 40;
int bonus = 20;
Console.WriteLine(points + bonus > 50); // True
points + bonus is 60, and 60 > 50 is True.
Assignment (=) is always last. That is why C# can calculate the whole right side first, and then store the result in the variable.