Skip to main content

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:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Bitwise Operators
  6. String Concatenation Operator
  7. Ternary Conditional Operator
  8. Type Operators
  9. Null-related Operators

Let's dive into each category.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numeric operands.

OperatorNameDescriptionExample
+AdditionAdds two operandsa + b
-SubtractionSubtracts right operand from left operanda - b
*MultiplicationMultiplies two operandsa * b
/DivisionDivides left operand by right operanda / b
%ModulusReturns the remainder after divisiona % b
++IncrementIncreases value by 1a++ or ++a
--DecrementDecreases value by 1a-- or --a

Let's see these operators in action:

csharp
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
tip

Note the difference between prefix and postfix increment/decrement:

  • ++a (prefix): Increments the value, then returns it
  • a++ (postfix): Returns the value, then increments it

Assignment Operators

Assignment operators assign values to variables. The basic assignment operator is =.

OperatorExampleEquivalent To
=a = ba = b
+=a += ba = a + b
-=a -= ba = a - b
*=a *= ba = a * b
/=a /= ba = a / b
%=a %= ba = a % b
&=a &= ba = a & b
|=a |= ba = a | b
^=a ^= ba = a ^ b
<<=a <<= ba = a << b
>>=a >>= ba = a >> b

Example:

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

OperatorNameDescriptionExample
==Equal toReturns true if both operands are equala == b
!=Not equal toReturns true if operands are not equala != b
>Greater thanReturns true if left operand is greater than right operanda > b
<Less thanReturns true if left operand is less than right operanda < b
>=Greater than or equal toReturns true if left operand is greater than or equal to right operanda >= b
<=Less than or equal toReturns true if left operand is less than or equal to right operanda <= b

Example:

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

OperatorNameDescriptionExample
&&Logical ANDReturns true if both operands are truea && b
||Logical ORReturns true if either operand is truea || b
!Logical NOTReturns the inverse of the operand's boolean value!a

Example:

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

OperatorNameDescription
&Bitwise ANDPerforms a bitwise AND operation
|Bitwise ORPerforms a bitwise OR operation
^Bitwise XORPerforms a bitwise exclusive OR operation
~Bitwise NOTPerforms a bitwise complement operation
<<Left ShiftShifts bits to the left
>>Right ShiftShifts bits to the right

Example:

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

csharp
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;

Console.WriteLine(fullName);

Output:

John Doe
tip

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

csharp
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:

OperatorDescriptionExample
typeofReturns the Type object for a typetypeof(int)
isChecks if an object is compatible with a typeobj is string
asPerforms conversion between compatible reference typesexpression as type

Example:

csharp
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

C# provides operators for working with nullable types:

OperatorNameDescription
??Null-coalescingReturns the left operand if it's not null; otherwise, returns the right operand
?.Null-conditionalPerforms a member access only if the operand is non-null
??=Null-coalescing assignmentAssigns the right operand to the left operand only if the left operand is null

Example:

csharp
// 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

csharp
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

csharp
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

  1. Write a program that calculates the area and perimeter of a rectangle using arithmetic operators.
  2. Create a temperature converter that converts between Celsius and Fahrenheit using operators.
  3. Implement a simple calculator that takes two numbers and an operator (+, -, *, /) as input.
  4. Write a program that uses bitwise operators to check if a number is even or odd.
  5. 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! :)