Member-only story
7 Things about C#: Operators
Every programming language has operators — the syntax that transforms values from one form to another. Think math, comparison, and bitwise transformations. Here, we discuss not only operators that are common to most general purpose languages, but also a few that are idiomatic to C#.
1 — Mathematical operators are algebraic
The general rule of using math operators is they evaluate from left to right, except that multiplication, *
, and division, /
, have precedence over addition, +
, and subtraction, -
. Here’s an example that expresses the nuances of operator precedence and associativity.
float result = 1 + 3 * 4;
The result
is 13. That’s because multiplication has precedence over addition. We multiply 3 * 4 to get 12 and then add 1 to get 13. That said, if you needed to add the 1 and 3 first, you can use this:
result = (1 + 3) * 4;
This time, the result
is 16 because parenthesis have precedence and allow you to manage the order of operations that you need.
Here’s a list of all of the C# operators. Operators at the top of the list have higher precedence than lower. Operators in the same category evaluate from left to right, as specified in code.