C# Operator precedence determines which to calculate first in an expression involving more than two operands. Operators in C# has their own priority during calculation, and the compiler calculates those with the highest priority first, following the next ones in priority. Consider this example:
number = 1 + 2 * 3 / 1;
If we don’t follow the order of which to calculate first and we calculate the expression from left to right, then 1 + 2 results to 3 multiplied by 3 yields 9 divided by 1 would give a final answer of 9 which is not the right answer (try it with a calculator). The compiler follows operator precedence. For example, the multiplication and division has higher precedence than addition and subtraction so we need to multiply 2 and 3 first which will result to 6 then divide it by 1 which is 6 and finally, we add 1 to 6 which results to 7. The result is then assigned to the variable thanks to the = operator which has lower precedence. The following table shows the precedence of some of the operators in C# from the highest precedence to the lowest.
|Highest||++, –, (used as prefixes); +, – (unary)|
|*, /, %|
|<, >, <=, >=|
|=, *=, /=, %=, +=, -=|
|Lowest||++, — (used as suffixes)|
Operators with a high precedence than other operators with lower precedence is calculated first. Notice that the ++ and — operators’ precedence depends on where you put those operators in an operand. For example, consider the expression below.
int number = 3; number1 = 3 + ++number; //results to 7 number2 = 3 + number++; //results to 6
In the first expression, the value of number is incremented first by 1 which makes it 4 and then it is added to 3 which results to a value of 7. On the second expression, the value of number which is 3 is added first to 3 which yields 6 that is added to variable number2. Just then would the number be incremented to 4.
To make C# operator precedence even more readable, we use parentheses.
number = ( 1 + 2 ) * ( 3 / 4 ) % ( 5 - ( 6 * 7 ));
The expressions inside each set of parentheses are evaluated first. Take note on expression inside the third set of parenthesis. The values inside of it use the normal operator precedence so 6 and 7 are multiplied first before subtracting it to 5. If two or more operators with the same level of precedence exists, then you can evaluate them based on their associativity. For example, in the expression:
number = 3 * 2 + 8 / 4;
has both * and / operators which have the same level of precedence. Their associativity is left-to-right so you must start with the one in the left the proceed to the next ones to the right. So we first multiply 3 and 2 and then divide 8 by 4. The results of the two expressions are added and then assigned to the number. You can check the following link for a full list of C# operator precedence and their associativity. For more information, refer to the following link: