C# Operators
Performing operations on variables and values
➕ What are Operators?
Operators are symbols that perform operations on variables and values in C#. They enable calculations, comparisons, logical operations, and assignments, forming the foundation of program logic and data manipulation.
// Using different operators
int a = 10;
int b = 5;
int sum = a + b; // Addition
int product = a * b; // Multiplication
bool isGreater = a > b; // Comparison
Console.WriteLine(sum); // Output: 15
Console.WriteLine(product); // Output: 50
Console.WriteLine(isGreater); // Output: True
Output:
15
50
True
Types of Operators
Arithmetic
Mathematical operations
int sum = 10 + 5;
int diff = 10 - 5;
Assignment
Assigning values to variables
int x = 10;
x += 5; // x = x + 5
Comparison
Comparing two values
bool result = 10 > 5;
bool equal = 10 == 10;
Logical
Combining boolean conditions
bool result = true && false;
bool or = true || false;
🔹 Arithmetic Operators
Arithmetic operators—addition (+), subtraction (-), multiplication (*), division (/), and modulus (%)—perform basic mathematical operations on numeric values. They are the foundation of all computational tasks, from simple calculations like 10 + 3 = 13 to complex algorithms. Modulus, for instance, finds remainders, useful in cryptography, loops, and data grouping. Mastery of these operators ensures efficient, readable code across finance, engineering, and everyday programming.
// Arithmetic operators
int a = 10;
int b = 3;
int addition = a + b; // Addition
int subtraction = a - b; // Subtraction
int multiplication = a * b; // Multiplication
int division = a / b; // Division (integer)
int modulus = a % b; // Remainder
Console.WriteLine("Addition: " + addition); // Output: 13
Console.WriteLine("Subtraction: " + subtraction); // Output: 7
Console.WriteLine("Multiplication: " + multiplication); // Output: 30
Console.WriteLine("Division: " + division); // Output: 3
Console.WriteLine("Modulus: " + modulus); // Output: 1
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
🔹 Assignment Operators
Assignment operators assign values to variables and include compound forms like +=, -=, *=, /=, and %=. For example, x += 5 adds 5 to x’s current value. These operators streamline code by combining arithmetic with assignment, reducing lines and enhancing readability. They are indispensable in loops, counters, and state management, enabling concise updates in game scores, financial totals, and dynamic data processing.
// Assignment operators
int x = 10; // Simple assignment
x += 5; // x = x + 5
Console.WriteLine(x); // Output: 15
x -= 3; // x = x - 3
Console.WriteLine(x); // Output: 12
x *= 2; // x = x * 2
Console.WriteLine(x); // Output: 24
x /= 4; // x = x / 4
Console.WriteLine(x); // Output: 6
x %= 4; // x = x % 4
Console.WriteLine(x); // Output: 2
Output:
15
12
24
6
2
🔹 Comparison Operators
Comparison operators like ==, !=, >, <, >=, and <= compare values and return booleans (true/false). They drive decision-making in if statements and loops. For example, 10 > 5 returns true, directing program flow. Essential for validation, filtering, and logic gates, these operators underpin user authentication, data sorting, and interactive features, ensuring programs respond correctly to varying conditions and inputs.
// Comparison operators
int a = 10;
int b = 5;
bool equal = (a == b); // Equal to
bool notEqual = (a != b); // Not equal to
bool greater = (a > b); // Greater than
bool less = (a < b); // Less than
bool greaterOrEqual = (a >= b); // Greater than or equal
bool lessOrEqual = (a <= b); // Less than or equal
Console.WriteLine("Equal: " + equal); // Output: False
Console.WriteLine("Not Equal: " + notEqual); // Output: True
Console.WriteLine("Greater: " + greater); // Output: True
Console.WriteLine("Less: " + less); // Output: False
Console.WriteLine("Greater or Equal: " + greaterOrEqual); // Output: True
Console.WriteLine("Less or Equal: " + lessOrEqual); // Output: False
Output:
Equal: False
Not Equal: True
Greater: True
Less: False
Greater or Equal: True
Less or Equal: False
🔹 Logical Operators
Logical operators—AND (&&), OR (||), and NOT (!)—combine boolean conditions for complex decision logic. AND requires all conditions true; OR needs at least one true; NOT inverts a value. For instance, age > 18 && hasLicense checks driving eligibility. These operators enable sophisticated control flows in algorithms, user permissions, and system checks, forming the backbone of reliable, multi-condition evaluations in software development.
// Logical operators
bool a = true;
bool b = false;
bool andResult = a && b; // AND - both must be true
bool orResult = a || b; // OR - at least one must be true
bool notResult = !a; // NOT - inverts the value
Console.WriteLine("AND: " + andResult); // Output: False
Console.WriteLine("OR: " + orResult); // Output: True
Console.WriteLine("NOT: " + notResult); // Output: False
// Practical example
int age = 25;
bool hasLicense = true;
bool canDrive = (age >= 18) && hasLicense;
Console.WriteLine("Can drive: " + canDrive); // Output: True
Output:
AND: False
OR: True
NOT: False
Can drive: True
🔹 Increment and Decrement
Increment (++) and decrement (--) operators adjust variables by 1, with prefix (++x) and postfix (x++) forms affecting evaluation order. Prefix changes the value before use; postfix after. Crucial for loops, counters, and iterations, they optimize performance in scenarios like array traversal, game timers, and pagination. Understanding their nuances prevents off-by-one errors, ensuring accurate increments in data processing and UI updates.
// Increment and Decrement operators
int x = 5;
x++; // Increment by 1 (x = x + 1)
Console.WriteLine(x); // Output: 6
x--; // Decrement by 1 (x = x - 1)
Console.WriteLine(x); // Output: 5
// Prefix vs Postfix
int a = 5;
int b = ++a; // Prefix: increment first, then assign
Console.WriteLine("a: " + a + ", b: " + b); // Output: a: 6, b: 6
int c = 5;
int d = c++; // Postfix: assign first, then increment
Console.WriteLine("c: " + c + ", d: " + d); // Output: c: 6, d: 5
Output:
6
5
a: 6, b: 6
c: 6, d: 5
🔹 String Concatenation Operator
The plus (+) operator concatenates strings, merging text like "Hello" + " " + "World!" into “Hello World!”. It automatically converts numbers to strings when mixed, enabling dynamic text generation. This operator is vital for creating messages, logging, UI labels, and data formatting in web apps, reports, and APIs, simplifying the construction of user-friendly outputs from disparate data sources.
// String concatenation with + operator
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
// Combining strings with numbers
int age = 25;
string message = "I am " + age + " years old";
Console.WriteLine(message); // Output: I am 25 years old
// Multiple concatenations
string greeting = "Hello" + " " + "World" + "!";
Console.WriteLine(greeting); // Output: Hello World!
Output:
John Doe
I am 25 years old
Hello World!
🔹 Operator Precedence
Operator precedence dictates the order of operations in expressions: multiplication/division before addition/subtraction. For example, 5 + 3 * 2 equals 11, not 16. Parentheses override precedence, making (5 + 3) * 2 equal 16. Understanding precedence prevents calculation errors, ensuring accurate results in mathematical models, financial formulas, and algorithmic logic. Clear use of parentheses enhances code readability and maintainability across complex expressions.
// Operator precedence
int result1 = 10 + 5 * 2; // Multiplication first
Console.WriteLine(result1); // Output: 20 (not 30)
int result2 = (10 + 5) * 2; // Parentheses first
Console.WriteLine(result2); // Output: 30
// Complex expression
int a = 10;
int b = 5;
int c = 2;
int result3 = a + b * c - 4 / 2;
// Order: b*c=10, 4/2=2, then 10+10-2=18
Console.WriteLine(result3); // Output: 18
// Using parentheses for clarity
int result4 = (a + b) * (c - 1);
Console.WriteLine(result4); // Output: 15
Output:
20
30
18
15