C# Operators
Introduction
Operators are symbols that tell the compiler to perform specific mathematical or logical operations. C# provides a rich set of operators that allow you to manipulate variables and values in your code. Understanding operators is fundamental to programming in C# as they form the building blocks of expressions and algorithms.
In this tutorial, we'll explore the various types of operators in C#, their syntax, and how they can be used in practical scenarios.
Types of Operators in C#
C# operators can be categorized into several groups:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- String Concatenation Operator
- Ternary Conditional Operator
- Type Operators
- Null-related Operators
Let's dive into each category.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric operands.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds two operands | a + b |
- | Subtraction | Subtracts right operand from left operand | a - b |
* | Multiplication | Multiplies two operands | a * b |
/ | Division | Divides left operand by right operand | a / b |
% | Modulus | Returns the remainder after division | a % b |
++ | Increment | Increases value by 1 | a++ or ++a |
-- | Decrement | Decreases value by 1 | a-- or --a |
Let's see these operators in action:
int a = 10;
int b = 3;
Console.WriteLine($"Addition: {a} + {b} = {a + b}");
Console.WriteLine($"Subtraction: {a} - {b} = {a - b}");
Console.WriteLine($"Multiplication: {a} * {b} = {a * b}");
Console.WriteLine($"Division: {a} / {b} = {a / b}");
Console.WriteLine($"Modulus: {a} % {b} = {a % b}");
int c = a++;
Console.WriteLine($"Postfix increment: c = a++ results in c = {c} and a = {a}");
int d = ++b;
Console.WriteLine($"Prefix increment: d = ++b results in d = {d} and b = {d}");
Output:
Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3
Modulus: 10 % 3 = 1
Postfix increment: c = a++ results in c = 10 and a = 11
Prefix increment: d = ++b results in d = 4 and b = 4
Note the difference between prefix and postfix increment/decrement:
++a
(prefix): Increments the value, then returns ita++
(postfix): Returns the value, then increments it
Assignment Operators
Assignment operators assign values to variables. The basic assignment operator is =
.
Operator | Example | Equivalent To |
---|---|---|
= | a = b | a = b |
+= | a += b | a = a + b |
-= | a -= b | a = a - b |
*= | a *= b | a = a * b |
/= | a /= b | a = a / b |
%= | a %= b | a = a % b |
&= | a &= b | a = a & b |
|= | a |= b | a = a | b |
^= | a ^= b | a = a ^ b |
<<= | a <<= b | a = a << b |
>>= | a >>= b | a = a >> b |
Example:
int x = 10;
Console.WriteLine($"Initial value: x = {x}");
// Addition assignment
x += 5; // Same as x = x + 5
Console.WriteLine($"After x += 5: x = {x}");
// Subtraction assignment
x -= 3; // Same as x = x - 3
Console.WriteLine($"After x -= 3: x = {x}");
// Multiplication assignment
x *= 2; // Same as x = x * 2
Console.WriteLine($"After x *= 2: x = {x}");
// Division assignment
x /= 4; // Same as x = x / 4
Console.WriteLine($"After x /= 4: x = {x}");
Output:
Initial value: x = 10
After x += 5: x = 15
After x -= 3: x = 12
After x *= 2: x = 24
After x /= 4: x = 6
Comparison Operators
Comparison operators compare two operands and return a boolean value (true
or false
).
Operator | Name | Description | Example |
---|---|---|---|
== | Equal to | Returns true if both operands are equal | a == b |
!= | Not equal to | Returns true if operands are not equal | a != b |
> | Greater than | Returns true if left operand is greater than right operand | a > b |
< | Less than | Returns true if left operand is less than right operand | a < b |
>= | Greater than or equal to | Returns true if left operand is greater than or equal to right operand | a >= b |
<= | Less than or equal to | Returns true if left operand is less than or equal to right operand | a <= b |
Example:
int a = 5, b = 10;
Console.WriteLine($"{a} == {b}: {a == b}");
Console.WriteLine($"{a} != {b}: {a != b}");
Console.WriteLine($"{a} > {b}: {a > b}");
Console.WriteLine($"{a} < {b}: {a < b}");
Console.WriteLine($"{a} >= {b}: {a >= b}");
Console.WriteLine($"{a} <= {b}: {a <= b}");
Output:
5 == 10: False
5 != 10: True
5 > 10: False
5 < 10: True
5 >= 10: False
5 <= 10: True
Logical Operators
Logical operators are used to combine conditional statements.
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical AND | Returns true if both operands are true | a && b |
|| | Logical OR | Returns true if either operand is true | a || b |
! | Logical NOT | Returns the inverse of the operand's boolean value | !a |
Example:
bool isEmployed = true;
bool hasHighIncome = false;
bool isEligibleForLoan = isEmployed && hasHighIncome;
Console.WriteLine($"Eligible for loan (AND): {isEligibleForLoan}");
bool canReceiveDiscount = isEmployed || hasHighIncome;
Console.WriteLine($"Can receive discount (OR): {canReceiveDiscount}");
bool isUnemployed = !isEmployed;
Console.WriteLine($"Is unemployed (NOT): {isUnemployed}");
Output:
Eligible for loan (AND): False
Can receive discount (OR): True
Is unemployed (NOT): False
Bitwise Operators
Bitwise operators manipulate individual bits of integer types.
Operator | Name | Description |
---|---|---|
& | Bitwise AND | Performs a bitwise AND operation |
| | Bitwise OR | Performs a bitwise OR operation |
^ | Bitwise XOR | Performs a bitwise exclusive OR operation |
~ | Bitwise NOT | Performs a bitwise complement operation |
<< | Left Shift | Shifts bits to the left |
>> | Right Shift | Shifts bits to the right |
Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
Console.WriteLine($"Bitwise AND: {a} & {b} = {a & b}"); // 0001 = 1
Console.WriteLine($"Bitwise OR: {a} | {b} = {a | b}"); // 0111 = 7
Console.WriteLine($"Bitwise XOR: {a} ^ {b} = {a ^ b}"); // 0110 = 6
Console.WriteLine($"Bitwise NOT: ~{a} = {~a}"); // Inverts all bits
Console.WriteLine($"Left Shift: {a} << 1 = {a << 1}"); // 1010 = 10
Console.WriteLine($"Right Shift: {a} >> 1 = {a >> 1}"); // 0010 = 2
Output:
Bitwise AND: 5 & 3 = 1
Bitwise OR: 5 | 3 = 7
Bitwise XOR: 5 ^ 3 = 6
Bitwise NOT: ~5 = -6
Left Shift: 5 << 1 = 10
Right Shift: 5 >> 1 = 2
String Concatenation Operator
The +
operator, when used with strings, concatenates (joins) them.
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
Output:
John Doe
For more efficient string concatenation, especially when joining multiple strings, consider using the string.Concat()
method or StringBuilder
class.
Ternary Conditional Operator
The ternary operator ?:
provides a shorthand way to write if-else statements.
Syntax: condition ? expressionIfTrue : expressionIfFalse
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine($"Status: {status}");
// Equivalent if-else statement
string statusWithIfElse;
if (age >= 18)
statusWithIfElse = "Adult";
else
statusWithIfElse = "Minor";
Output:
Status: Adult
Type Operators
C# provides several operators that work with types:
Operator | Description | Example |
---|---|---|
typeof | Returns the Type object for a type | typeof(int) |
is | Checks if an object is compatible with a type | obj is string |
as | Performs conversion between compatible reference types | expression as type |
Example:
object obj = "Hello";
// typeof operator
Type stringType = typeof(string);
Console.WriteLine($"String type: {stringType.Name}");
// is operator
bool isString = obj is string;
Console.WriteLine($"obj is string: {isString}");
// as operator
string str = obj as string;
if (str != null)
Console.WriteLine($"String value: {str}");
Output:
String type: String
obj is string: True
String value: Hello
Null-related Operators
C# provides operators for working with nullable types:
Operator | Name | Description |
---|---|---|
?? | Null-coalescing | Returns the left operand if it's not null; otherwise, returns the right operand |
?. | Null-conditional | Performs a member access only if the operand is non-null |
??= | Null-coalescing assignment | Assigns the right operand to the left operand only if the left operand is null |
Example:
// Null-coalescing operator
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine($"Welcome, {displayName}!");
// Null-conditional operator
string text = null;
int? length = text?.Length;
Console.WriteLine($"Length: {length ?? 0}");
// Null-coalescing assignment operator (C# 8.0+)
string username = null;
username ??= "DefaultUser";
Console.WriteLine($"Username: {username}");
Output:
Welcome, Guest!
Length: 0
Username: DefaultUser
Real-World Examples
Example 1: Calculating Discounts for an E-commerce Application
decimal CalculateDiscount(decimal price, bool isPremiumCustomer, int purchaseCount)
{
// Base discount
decimal discount = 0;
// Quantity discount: 5% off for 10+ items
if (purchaseCount >= 10)
discount += 0.05m;
// Premium customer discount: additional 10%
if (isPremiumCustomer)
discount += 0.10m;
// New price after discount
decimal finalPrice = price * (1 - discount);
// Apply additional $5 off if price is over $100 (using ternary operator)
finalPrice -= (finalPrice > 100) ? 5 : 0;
return finalPrice;
}
// Usage
decimal regularPrice = 120.00m;
decimal discountedPrice = CalculateDiscount(regularPrice, true, 12);
Console.WriteLine($"Regular price: ${regularPrice}");
Console.WriteLine($"Final price after discounts: ${discountedPrice}");
Output:
Regular price: $120.00
Final price after discounts: $97.00
Example 2: Processing User Input with Validation
bool TryGetUserAge(string input, out int age)
{
// Try parsing the input to an integer
bool isValid = int.TryParse(input, out age);
// Check if age is within a valid range
isValid = isValid && (age >= 0 && age <= 120);
return isValid;
}
void ProcessUserInput(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Error: Input cannot be empty.");
return;
}
int age;
if (TryGetUserAge(input, out age))
{
string category = (age < 13) ? "Child" :
(age < 20) ? "Teenager" :
(age < 65) ? "Adult" : "Senior";
Console.WriteLine($"Age {age} categorized as: {category}");
}
else
{
Console.WriteLine("Error: Invalid age input.");
}
}
// Usage examples
ProcessUserInput(""); // Error case
ProcessUserInput("abc"); // Error case
ProcessUserInput("25"); // Valid case
ProcessUserInput("150"); // Error case (out of range)
Output:
Error: Input cannot be empty.
Error: Invalid age input.
Age 25 categorized as: Adult
Error: Invalid age input.
Summary
In this tutorial, we've covered the various operators available in C#:
- Arithmetic operators for mathematical calculations
- Assignment operators for assigning values to variables
- Comparison operators for comparing values
- Logical operators for combining conditions
- Bitwise operators for manipulating individual bits
- String concatenation for joining strings
- Ternary operator for concise conditional expressions
- Type operators for working with types
- Null-related operators for handling nullable types
Understanding these operators is crucial for writing efficient and readable C# code. They form the foundation for expressions and logic in your programs.
Additional Resources
Exercises
- Write a program that calculates the area and perimeter of a rectangle using arithmetic operators.
- Create a temperature converter that converts between Celsius and Fahrenheit using operators.
- Implement a simple calculator that takes two numbers and an operator (+, -, *, /) as input.
- Write a program that uses bitwise operators to check if a number is even or odd.
- Create a method that uses the null-conditional and null-coalescing operators to safely access properties in a potentially null object.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)