Understanding C# Operators: Precedence, Associativity, and Operator Types
Learn about the different types of operators in C# (arithmetic, logical, bitwise, etc.), their precedence, and associativity. This tutorial provides a comprehensive guide to C# operators, essential knowledge for writing correct and efficient C# code.
Operators in C#
Operators are symbols that perform operations on one or more operands (values or variables). C# supports various types of operators for different operations (arithmetic, logical, bitwise, etc.). Understanding operator precedence and associativity is crucial for writing correct code.
Types of Operators in C#
- Arithmetic Operators: Perform arithmetic calculations (`+`, `-`, `*`, `/`, `%`).
- Relational Operators: Compare values (`<`, `>`, `<=`, `>=`, `==`, `!=`).
- Logical Operators: Combine boolean expressions (`&&`, `||`, `!`).
- Bitwise Operators: Perform bitwise operations (`&`, `|`, `^`, `~`, `<<`, `>>`).
- Assignment Operators: Assign values (`=`, `+=`, `-=`, etc.).
- Unary Operators: Operate on a single operand (`+`, `-`, `++`, `--`, `!`).
- Ternary Operator: A conditional operator (`?:`).
- Other Operators: Includes `as`, `is`, `typeof`, `nameof`, etc.
Operator Precedence and Associativity
Operator precedence determines the order of operations. For example, multiplication and division have higher precedence than addition and subtraction. Associativity specifies the direction of evaluation (left-to-right or right-to-left).
Example: `10 + 5 * 5` evaluates to 35 because multiplication is performed before addition.
C# Operator Precedence Table
Category (by precedence) | Operator(s) | Associativity |
---|---|---|
Unary | + - ! ~ ++ -- (type)* & sizeof |
Right-to-left |
Multiplicative | * / % |
Left-to-right |
Additive | + - |
Left-to-right |
Shift | << >> |
Left-to-right |
Relational | < > <= >= |
Left-to-right |
Equality | == != |
Left-to-right |
Logical AND | & |
Left-to-right |
Logical XOR | ^ |
Left-to-right |
Logical OR | | |
Left-to-right |
Conditional AND | && |
Left-to-right |
Conditional OR | || |
Left-to-right |
Null Coalescing | ?? |
Left-to-right |
Conditional (ternary) | ?: |
Right-to-left |
Assignment | = *= /= %= += -= <<= >>= &=amp; ^= |= |
Right-to-left |