Tuesday, December 11, 2018 13:26

Operator precedence

If you still remember from math class (yeah, right! 😀 ), some operators have precedence over others, meaning that multiplication is more important than addition and will be calculated first. Operator precedence should always be remembered when dealing with more than two operands.

As in mathematics, you can force the change of operator precedence by using parenthesis. Lets consider the following example:

If the average (or mean value) would be calculated, it should be 10. But if you let C# evaluate that expression, the result would be 20, because:

That happens because division has a higher precedence than addition, and its calculated first. In order to correctly calculate the mean value, you have to “force” a different order of operation:

The reason why the above example works is because parenthesis () have a higher operator precedence than any other operator, in C#. So, by using them, we force the compiler to first evaluate the expression inside the parenthesis, and then perform the division.

Here is a table showing the operator precedence in C#, from highest to lowest priority:

As a general rule, you should always use parenthesis whenever the expression would be ambiguous:



Tags: ,

Leave a Reply