In C#, operators are acted on based on the order of precedence of the language. As a developer, you should use parentheses to specifically set the order of precedence, as well as to make your code easier to read (see the "Logical Operators" section earlier in this chapter for examples of using parentheses).
When the compiler encounters an expression with multiple operators, the precedence table is used to evaluate the order of operations. If an operand is between two operators that have the same precedence, the associativity of the operators is used to determine the order of operations. Except for the assignment operator, all binary operators are left associative. The assignment operator (=) and the ternary operator (?:) are right associative. For example, the following:
a = b = c;
is equal to
a = (b = c);
Table 2-2 shows the precedence table for C# operators.
|
Category |
Operator |
Description |
|---|---|---|
|
Primary |
(x) |
Grouping |
|
x.y |
Member access |
|
|
−> |
Struct pointer member access |
|
|
f(x) |
Method calla |
|
|
a[x] |
Indexing |
|
|
++ |
Postincrement |
|
|
x−− |
Postdecrement |
|
|
new |
Constructor |
|
|
stackalloc |
Array stack allocation |
|
|
typeof |
Type retrieval |
|
|
sizeof |
Struct size retrieval |
|
|
checked |
Arithmetic check on |
|
|
unchecked |
Arithmetic check off |
|
|
Unary |
+ |
Positive value |
|
− |
Negative value |
|
|
! |
Not |
|
|
~ |
Bitwise complement |
|
|
++x |
Preincrement |
|
|
−−x |
Predecrement |
|
|
(T)x |
Type casting |
|
|
Value at address—dereference | ||
|
& |
Address of value |
|
|
MultiplicativeMultiply | ||
|
/ |
Division |
|
|
% |
Division remainder |
|
|
Additive |
+ |
Add |
|
− |
Subtract |
|
|
Shift |
<< |
Shift left |
|
>> |
Shift right |
|
|
Relational |
< |
Less than |
|
> |
Greater than |
|
|
<= |
Less than or equal |
|
|
>= |
Greater than or equal |
|
|
is |
Type equality |
|
|
Equality |
== |
Equal |
|
!= |
Not equal |
|
|
Logical Bitwise |
& |
AND |
|
^ |
XOR |
|
|
| |
OR |
|
|
Logical Boolean |
&& |
And |
|
|| |
Or |
|
|
?: |
Returns one of two values depending on the value of a Boolean expression |
|
|
Assignment |
= *= /= |
Assign/modify |
|
+= −= <<= | ||
|
>>= &= ^= | ||
|
|= |