The order of terms and expressions, in any programming language, determine the outcome of your evaluation.The operators’ precedence in C# determines how the grouping of these terms and expressions happen. This guide will walk you through the essentials as to what you must know to wield this technique and create semantically correct apps.
An operator is nothing more than a program element that is applied to at least one operand or more.
There are different types of operators:
These define how many operands an operator takes. Unary take only one, the Binary takes two, and the Ternary take 3 operands.
There are two types of associativities:
The operator precedence is meaningful only if there are higher and lower precedence operators in an expression.
In this case, the precedence is from Left to Right.
int x = 7 - 3 + 4 - 6;
This case shows the stronger multiplication’s precedence over the additive operators.
int x = 7 + 3 * 2;
Right to Left:
Simple and compount assignment
Every other operator that you face,except the above mentioned three bullet points, have the Left to Right order. When you are combining these, you need to watch out.
As in every other programming language, there is a way to modify the order of evaluation. The order imposed by operator precedence and associativity can be changed by using parentheses.
Let's take a look at the following example.
2 + 3 * 2
By default, this evaluates to 8. However, with parenthesis, we could modify the result to be equal to 10.
(2 + 3) * 2
This guide clarified the basic knowledge you must be aware of in order to efficiently use operators, along with understand and effectively track down the issues that might raise from not properly evaluating of the expression regarding their order. If you keep in mind the above rules I described, it will help you write semantically correct code and allow you to spend more time improving the application quality than tracking down mysterious bugs.