C# Operator Precedence

By now, we introduced many operators and the examples. But if we put them together, we need to know which operators are calculated first. The following table is showing the operator precedence from high to low. But in each category, the operators have the same precedence.

CategoryOperatorsAssociativity
Primary. () [] x++ x-- new typeof checked unchecked ->From left to right
Unary+ - ! ~ ++x --x (Cast) & *From right to left
Multiplicative* / %From left to right
Additive+ -From left to right
Shift<< >>From left to right
Relational & type check< > <= >= is asFrom left to right
Equality== !=From left to right
Logical/Bitwise AND&From left to right
Logical/Bitwise XOR^From left to right
Logical/Bitwise OR|From left to right
Conditional AND&&From left to right
Conditional OR||From left to right
Null-coalescing??From right to left
Conditional?:From right to left
Assignment & lambda= += -= *= /= %= &= |= ^= <<= >>= =>From right to left

Some of the operators will be introduced in the later sections.

Example 01-14-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace TestOperatorPrecedence
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2, b = 3, c = 4, d;
            d = a + b * ++c;
            Console.WriteLine("First: d = {0}", d);
			
            c --;
            d = (a + b) * ++c;
            Console.WriteLine("Second: d = {0}", d);

            c --;
            string result;
            result = a==2|b==3&c==5 ? "true" : "false";
            Console.WriteLine("First: result = {0}", result);
			
            result = (a==2|b==3)&c==5 ? "true" : "false";
            Console.WriteLine("Second: result = {0}", result);
            Console.Read();
        }
    }
}

Output

First: d = 17
Second: d = 25
First: result = true
Second: result = false
  • Line 10: Firstly ++c is calcualted to make c plus 1. Secondly b * c = 3 * 5 = 15. Thirdly d = a + 15 = 17. The statement equals to the following statement.
  • d = a + (b * (++c));
  • Line 13: After this statement c = 4 again.
  • Line 14: We'll use round bracket to change evaluation order. So the + and ++ operator evaluate first and then * operator. So the result is 25.
  • Line 17: Set c = 4 again.
  • Line 19: b==3&c==5 is evaluated first and returned false then evaluate a==2|false and get the result. The statement is equivalent to that below.
  • result = a==2|(b==3&c==5) ? "true" : "false";
  • Line 22: (a==2|b==3) is evaluate first and get true then evaluate true & c==5 and the result is false.
Note Note
It is good to use () operator if you are not sure the operator precedence order of the expression.