C# - Operators
C# - Operators
Section titled “C# - Operators”An operator is a symbol that instructs the compiler to perform a specific mathematical, logical, or other manipulation. C# offers a rich set of built-in operators, which can be grouped into the following categories:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise and Shift Operators
- Assignment Operators
- Miscellaneous Operators (Type-testing, Null-coalescing, etc.)
Arithmetic Operators
Section titled “Arithmetic Operators”These operators perform standard mathematical calculations. Assume int a = 10; and int b = 3;.
| Operator | Description | Example |
|---|---|---|
+ | Addition | a + b is 13 |
- | Subtraction | a - b is 7 |
* | Multiplication | a * b is 30 |
/ | Division | a / b is 3 (integer division truncates the remainder) |
% | Modulus (Remainder) | a % b is 1 |
++ | Increment by 1 | a++ uses a then increments it to 11 |
-- | Decrement by 1 | a-- uses a then decrements it to 9 |
// Exampleint x = 10, y = 4;Console.WriteLine($"Addition: {x + y}"); // Output: 14Console.WriteLine($"Division: {x / y}"); // Output: 2Console.WriteLine($"Modulus: {x % y}"); // Output: 2
// For floating-point division, cast one operand to a float/doubleConsole.WriteLine($"Floating-point Division: {(double)x / y}"); // Output: 2.5Relational Operators
Section titled “Relational Operators”These operators compare two operands and return a bool value (true or false). Assume int a = 10; and int b = 20;.
| Operator | Description | Example |
|---|---|---|
== | Equal to | a == b is false |
!= | Not equal to | a != b is true |
> | Greater than | a > b is false |
< | Less than | a < b is true |
>= | Greater than or equal to | a >= b is false |
<= | Less than or equal to | a <= b is true |
// Exampleint a = 20, b = 15;Console.WriteLine($"Is a > b? {a > b}"); // Output: TrueConsole.WriteLine($"Is a == b? {a == b}"); // Output: FalseLogical Operators
Section titled “Logical Operators”These operators are used to combine bool expressions. They are fundamental for creating complex conditions in if statements and loops.
| Operator | Description | Example (A is true, B is false) |
|---|---|---|
&& | Logical AND (short-circuiting) | A && B is false |
|| | Logical OR (short-circuiting) | A || B is true |
! | Logical NOT (negation) | !A is false |
// Examplebool hasKey = true;int coins = 50;
bool canOpenChest = hasKey && coins >= 100;Console.WriteLine($"Can open chest? {canOpenChest}"); // Output: FalseAssignment Operators
Section titled “Assignment Operators”These operators assign a value to a variable. The compound assignment operators provide a shorthand for performing an operation and assignment in one step.
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 5; | x = 5; |
+= | x += 5; | x = x + 5; |
-= | x -= 5; | x = x - 5; |
*= | x *= 5; | x = x * 5; |
/= | x /= 5; | x = x / 5; |
??= | x ??= 5; | x = (x ?? 5); (Assigns only if x is null) |
// Exampleint score = 100;score += 50; // Add 50 pointsConsole.WriteLine($"Final Score: {score}"); // Output: 150
string name = null;name ??= "Guest"; // Assigns "Guest" because name is nullConsole.WriteLine($"User: {name}"); // Output: GuestMiscellaneous Operators
Section titled “Miscellaneous Operators”C# includes several other powerful operators for various tasks.
| Operator | Name | Description |
|---|---|---|
?: | Ternary Conditional | A shorthand for an if-else statement. condition ? val_if_true : val_if_false. |
?? | Null-Coalescing | Returns the left-hand operand if it’s not null; otherwise, it returns the right-hand operand. |
?. | Null-Conditional (Elvis) | Safely access members. If the operand is null, the expression evaluates to null instead of throwing an exception. |
typeof() | Type Of | Returns the System.Type object for a type. |
sizeof() | Size Of | Returns the size in bytes of a value type. Requires an unsafe context for non-primitive types. |
nameof() | Name Of | Returns the name of a variable, type, or member as a string literal. |
is | Type Check | Checks if an object is of a certain type, returning true or false. |
as | Type Conversion | Converts an object to a specific type without throwing an exception; returns null if the conversion fails. |
// Ternary and Null-Coalescing Exampleint age = 21;string status = (age >= 18) ? "Adult" : "Minor";Console.WriteLine($"Status: {status}"); // Output: Adult
string displayName = null;string username = displayName ?? "User123";Console.WriteLine($"Username: {username}"); // Output: User123
// Null-Conditional Examplestring[] names = { "Alice", "Bob" };//string[] names = null;int? count = names?.Length; // count is int? (nullable int)Console.WriteLine($"Number of names: {count ?? 0}"); // Safely gets length or defaults to 0Operator Precedence
Section titled “Operator Precedence”Operator precedence dictates the order of evaluation in complex expressions. For example, * has higher precedence than +.
While it’s useful to know the rules, the best practice is to use parentheses () to make your intent clear. This improves code readability and prevents subtle bugs.
// Unclear: relies on reader knowing precedenceint result1 = 3 + 4 * 5; // 23
// Clear: the order is explicit and self-documentingint result2 = 3 + (4 * 5); // 23
Console.WriteLine($"Result 1: {result1}, Result 2: {result2}");For a detailed breakdown of all operators and their precedence levels, please refer to our dedicated C# Operator Precedence tutorial.