Tip:
Highlight text to annotate it
X
In this section we'll take a look at the operators in C# that are used to operate on numbers.
They can be grouped into five types: arithmetic, assignment, comparison, logical, and bitwise
operators.
First, we have the four basic arithmetic operations, as well as modulus to get the division remainder.
Notice that the division sign gives an incorrect result here. This is because it operates on
two integer values and will therefore round the result and return an integer. To get the
correct value we need to explicitly convert one of the numbers to a floating-point number.
A common use of the assignment and arithmetic operators is to operate on a variable and
then to save the result back into that same variable. These operations can be shortened
with the combined assignment operators.
Another common operation is to increment or decrement a variable by one.
This can be simplified with the increment (++) and decrement (--) operators.
Both of these can either be used before or after a variable.
The result on the variable is the same whichever we use. The difference is that the post-operator
returns the original value before it changes the variable while the pre-operator changes
the variable first and then returns the value.
Next, there's the comparison operators that compares two values and returns either true
or false.
Used together with these we have the logical operators. Logical and (&&) evaluates to true
if both the left and right side are true and logical or (||) is true if either the left
or right side is true. To invert a boolean result we also have logical not (!). Note
that for both "logical and" and "logical or" the right hand side won't be evaluated if
the result is already determined by the left side.
Lastly, we have the bitwise operators, which allow us to manipulate individual bits inside
of an integer. For example, the and operator (&) makes the
resulting bit 1 if the bits on both sides of the operator are set. These bitwise operators
also have shorthand assignment operators.
Now let's look at operator precedence. In C#, expressions are normally evaluated from
left to right. However, different operators also have different precedents. For example,
the logical and operator binds weaker than the relational operators which in turn binds
weaker than the arithmetic operators. To avoid having to learn the precedents we can instead
use parenthesis to decide what part of the expression will be evaluated first.