Sonali Gogate
C# Operators
The C# operator semantics, like the operator semantics in most of the
programming languages, follow the basic rules and notations of semantics of
mathematical operators.
The basic operators of C# are —
Addition (+)
Deletion (-)
Multiplication (*)
Division (/)
Modulus (%)
Assignment (=)
Also —
Unary Plus (+)
and
Unary Minus (-)
Most operators work only on numeric data types (like
int, float, double, long etc.) Exceptions to these are == and !=
Other C# operators are
+= (like C++, if we have a+=b, it means a = a+b)
++ (increment by 1)
-- (decrement by 1)
Using Operators in Expressions
When a single expression contains multiple operators, the execution sequence
is decided by the priority of each operator. The rules which a compiler follows
for determining the sequence of operator execution is known as "operator
precedence".
In case there are 2 operators of same "precedence", then the
evaluation is done based on its associativity (that is based on whether it is
left or right associative). For example in the following expression —
35 — 20 — 5
Since (-) is left-associative, (35-20)
gets evaluated to yield 15 and then
(15-5) is evaluated.
In C# all the binary operators except for = are left-associative.
= though is necessarily right-associative.
Operator Precedence in C#
Here is a table that shows the C# operators in descending operator
precedence —
Operator Type |
Operators |
Primary |
(x), x.y, f(x), a |
Unary |
+, -, !, ~, ++x, --x, (T)x |
Multiplicative |
*, /, % |
Additive |
+, - |
Shift |
<<, >> |
Relational |
<, >, <=, >=, is |
Equality |
== |
Logical AND |
& |
Logical XOR |
^ |
Logical OR |
| |
Conditional AND |
&& |
Conditional OR |
|| |
Conditional |
?: |
Assignment |
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= |
If one wishes to change the evaluation of expressions (that is not evaluate
them in the order of precedence), it can be done with use of parentheses. For
example to change the evaluation order in the following expression and get the
addition done before the multiplication
6 + 3 * 4 — (this would evaluate to 18)
We can write it as
(6 + 3) * 4 — (this would evaluate to 36).
As you can see from the operators in the table above, most of them were
available in earlier languages like C++, and in that sense the operators and
expressions in C# are not any different from those in C++.
There are, a couple of operators, which I think are worth talking about —
specifically 2 primary operators, namely checked
and unchecked. These 2 are used to
control overflow checking of mathematical operations. We talk more about them
under "Error Handling".
(The author is a technical evangalist with Microsoft India)