C# Operator Precedence

C# Operator Precedence

When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:

10 + 20 * 10 = 300

This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:

int x;

x = 10 + 20 * 10;

Console.WriteLine (x)

The above code, when compiled and executed, will output the result 210.

This is a direct result of operator precedence. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.

Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. 

For example:

int x;

x = (10 + 20) * 10;

Console.WriteLine (x)

In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.

In order to understand the working of operator precedence in C#, we need to know the order of precedence of operators.

The following table outlines the C# operator precedence order from highest precedence to lowest:

CategoryOperator(s)
Postfix / Prefix() , [] , -> , . , ++ ,
Unary+ , , ! , ~ , ++ , , (type)* , &sizeof
Multiplicative* , / , %
Additive+ , -
Shift<< , >>
Relational< , <= , > , >=
Equality== , !=
Bitwise AND&
Bitwise XOR^
Bitwise OR|
Logical AND&&
Logical OR||
Conditional?:
Assignment= , += , -= , *= , /= , %= , >>= , <<= , &= , ^= , |=
Comma,

 

C# Operator Precedence Example

C# program to demonstrate the precedence of operators.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int res;
            int x = 8, y = 10, z = 6;
            res = --x * y - ++z;
            Console.WriteLine(res);
            bool res1;
            res1 = y >= z + x;
            Console.WriteLine(res1);
            Console.ReadLine();
        }
    }
}

Output:

Example of Operator Precedence in C#

In the above program, in the expression –x * y – ++z, –x and ++z is evaluated first and then the resulting value of –x is multiplied with y and the resulting value is subtracted from the resulting value of ++z as per the operator precedence in c#.

And in the expression y >= z + x, z+x is evaluated first and the resulting value is compared with the value of y as per the operator precedence in c#.