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:

1 |
average = 5 + 10 + 15 / 3; |

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:

1 2 3 4 |
average = 5 + 10 + 15 / 3; = 5 + 10 + 5; = 15 + 5; = 20; |

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:

1 2 3 4 |
average = (5 + 10 + 15) / 3; = (15 + 15) / 3; = (30) / 3; = 10; |

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(,) ++, -- (as postfix), new, (type), typeof, sizeof ++, -- (as prefix), +, - (unary), !, ~ *, /, % + (string concatenation) +, - <<, >> <, >, <=, >=, is, as ==, != &, ^, | && || ?:, ?? =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= |

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

1 2 3 4 5 |
// Ambiguous x + y / 2 // Unambiguous, cleaner, recommended way x + (y / 2) |

*The concepts explained in this lesson are also shown visually as part of the following video:*

Tags: operator precedence, operators