Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

The Order Is of the Utmost Importance

Jan 31, 2020 • 2 Minute Read

Introduction

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.

What Is an Operator?

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:

  1. Unary
  2. Binary
  3. Ternary

These define how many operands an operator takes. Unary take only one, the Binary takes two, and the Ternary take 3 operands.

Associativity

There are two types of associativities:

  1. Left to Right
  2. Right to Left

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;
    

The Order to Remember

Right to Left:

  1. Unary

    • sizeof & * + - ~ ! ++ -- (prefix)
    • typecasts
  2. Conditional-expression

    • ? :
  3. 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.

Parentheses

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
    

Conclusion

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.