Author avatar

Dániel Szabó

The Order Is of the Utmost Importance

Dániel Szabó

  • Jul 26, 2019
  • 2 Min read
  • 30 Views
  • Jul 26, 2019
  • 2 Min read
  • 30 Views
Languages Frameworks and Tools
C#

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.

1
int x = 7 - 3 + 4 - 6;
csharp

This case shows the stronger multiplication’s precedence over the additive operators.

1
int x = 7 + 3 * 2;
csharp

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.

1
2 + 3 * 2
csharp

By default, this evaluates to 8. However, with parenthesis, we could modify the result to be equal to 10.

1
(2 + 3) * 2
csharp

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.

0