Operators in C#
Apply arithmetic, relational, logical, assignment, bitwise operators, null-coalescing (?? and ??=), null-conditional (?.), and operator precedence.
Arithmetic Operators
1. + - * / %
The five basic arithmetic operators — addition, subtraction, multiplication, division, and modulus.
2. Increment and Decrement
`++` and `--` increment or decrement by 1. Prefix form changes before use; postfix changes after.
Relational (Comparison) Operators
1. == and !=
`==` checks value equality. `!=` checks inequality. For objects, `==` compares references unless overridden.
2. < > <= >=
Compare numeric values with relational operators.
Logical Operators
1. && || !
Logical AND, OR, and NOT for combining conditions.
2. Short-circuit Behaviour
`&&` stops evaluating if the left side is `false`. `||` stops if the left side is `true`. This prevents unnecessary work or null errors.
Assignment Operators
1. = Assignment
The `=` operator assigns a value to a variable.
2. Compound Assignment
Combine an operation with assignment: `+=`, `-=`, `*=`, `/=`, `%=`.
Null Operators
1. Null-Coalescing (?? and ??=)
`??` returns the right-hand value if the left is null. `??=` assigns only if the variable is null.
2. Null-Conditional (?. and ?[])
`?.` accesses a member only if the object is not null — returns null instead of throwing `NullReferenceException`.
Type Operators
1. is and as
`is` checks if a value is of a type. `as` attempts a cast and returns null instead of throwing on failure.
2. typeof
`typeof(T)` returns the `Type` object for a type at compile time.
Bitwise Operators
1. & | ^ ~ (AND, OR, XOR, NOT)
Bitwise operators work on the binary representation of integers.
2. << >> (Left Shift, Right Shift)
Shift bits left or right. Left shift multiplies by 2; right shift divides by 2.
Operator Precedence
1. Precedence Example
Operators with higher precedence are evaluated first. Use parentheses to make intent explicit.
2. Operator Precedence Table
A reference table of C# operator precedence from highest to lowest.