Skip to content

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.)

These operators perform standard mathematical calculations. Assume int a = 10; and int b = 3;.

OperatorDescriptionExample
+Additiona + b is 13
-Subtractiona - b is 7
*Multiplicationa * b is 30
/Divisiona / b is 3 (integer division truncates the remainder)
%Modulus (Remainder)a % b is 1
++Increment by 1a++ uses a then increments it to 11
--Decrement by 1a-- uses a then decrements it to 9
// Example
int x = 10, y = 4;
Console.WriteLine($"Addition: {x + y}"); // Output: 14
Console.WriteLine($"Division: {x / y}"); // Output: 2
Console.WriteLine($"Modulus: {x % y}"); // Output: 2
// For floating-point division, cast one operand to a float/double
Console.WriteLine($"Floating-point Division: {(double)x / y}"); // Output: 2.5

These operators compare two operands and return a bool value (true or false). Assume int a = 10; and int b = 20;.

OperatorDescriptionExample
==Equal toa == b is false
!=Not equal toa != b is true
>Greater thana > b is false
<Less thana < b is true
>=Greater than or equal toa >= b is false
<=Less than or equal toa <= b is true
// Example
int a = 20, b = 15;
Console.WriteLine($"Is a > b? {a > b}"); // Output: True
Console.WriteLine($"Is a == b? {a == b}"); // Output: False

These operators are used to combine bool expressions. They are fundamental for creating complex conditions in if statements and loops.

OperatorDescriptionExample (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
// Example
bool hasKey = true;
int coins = 50;
bool canOpenChest = hasKey && coins >= 100;
Console.WriteLine($"Can open chest? {canOpenChest}"); // Output: False

These operators assign a value to a variable. The compound assignment operators provide a shorthand for performing an operation and assignment in one step.

OperatorExampleEquivalent 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)
// Example
int score = 100;
score += 50; // Add 50 points
Console.WriteLine($"Final Score: {score}"); // Output: 150
string name = null;
name ??= "Guest"; // Assigns "Guest" because name is null
Console.WriteLine($"User: {name}"); // Output: Guest

C# includes several other powerful operators for various tasks.

OperatorNameDescription
?:Ternary ConditionalA shorthand for an if-else statement. condition ? val_if_true : val_if_false.
??Null-CoalescingReturns 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 OfReturns the System.Type object for a type.
sizeof()Size OfReturns the size in bytes of a value type. Requires an unsafe context for non-primitive types.
nameof()Name OfReturns the name of a variable, type, or member as a string literal.
isType CheckChecks if an object is of a certain type, returning true or false.
asType ConversionConverts an object to a specific type without throwing an exception; returns null if the conversion fails.
// Ternary and Null-Coalescing Example
int 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 Example
string[] 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 0

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 precedence
int result1 = 3 + 4 * 5; // 23
// Clear: the order is explicit and self-documenting
int 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.