16. Precedence#

In the world of programming, not all operators are equal. Some have higher priority than others. This is what we call ‘operator precedence’.

Operator precedence determines the order in which operations are performed when different operators are present within an expression. Just like in algebra, multiplication and division operators have higher precedence than addition and subtraction. So, in an expression like 3 + 4 * 5, the multiplication is performed first, resulting in 3 + 20, and then the addition is done, leading to the result 23.

It’s important to know about operator precedence because it affects how an expression is evaluated. Misunderstanding precedence can lead to unexpected results. If you want to override the default precedence, you can use parentheses. For instance, if you want the addition to happen first in the previous expression, you can write (3 + 4) * 5, which gives 35.

C# has a specific order of precedence for its operators. The complete list can be found in the C# documentation.

../_images/cover-precedence.jpg

Fig. 16.1 Not all operators are equal, so when mixing operators you must keep precedence in mind, since some are executed before others.#