Skip to content

Operators

Operators are symbols that tell the compiler to perform specific mathematical or logical operations. C# provides a rich set of operators for various operations.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numeric operands.

csharp
int a = 10, b = 3;
int sum = a + b;      // Addition: 13
int diff = a - b;     // Subtraction: 7
int product = a * b;  // Multiplication: 30
int quotient = a / b; // Division: 3
int remainder = a % b;// Modulus: 1

Comparison Operators

Comparison operators compare two values and return a boolean result.

csharp
bool isEqual = a == b;     // Equal to: false
bool notEqual = a != b;    // Not equal to: true
bool greater = a > b;      // Greater than: true
bool less = a < b;         // Less than: false
bool greaterEqual = a >= b;// Greater than or equal: true
bool lessEqual = a <= b;   // Less than or equal: false

Logical Operators

Logical operators perform boolean logic operations.

csharp
bool and = true && false;  // Logical AND: false
bool or = true || false;   // Logical OR: true
bool not = !true;         // Logical NOT: false

// Short-circuit evaluation
bool result = CheckA() && CheckB();  // CheckB() only called if CheckA() is true

Assignment Operators

Assignment operators assign values to variables, often combining assignment with arithmetic.

csharp
int x = 5;        // Simple assignment
x += 3;           // Add and assign: x = x + 3
x -= 2;           // Subtract and assign: x = x - 2
x *= 4;           // Multiply and assign: x = x * 4
x /= 2;           // Divide and assign: x = x / 2
x %= 3;           // Modulus and assign: x = x % 3