Skip to main content

.NET C# Operators

Introduction

Operators are special symbols that perform specific operations on one, two, or more operands and then return a result. In C#, operators are the foundation of any programming logic you'll write, allowing you to perform calculations, compare values, assign data, and control the flow of your programs.

This guide will walk you through the various operators available in C#, explain how they work, and provide practical examples that you can apply in your own code.

Types of C# Operators

C# has a rich set of operators categorized based on their functionality. Let's explore each category:

1. Arithmetic Operators

Arithmetic operators perform mathematical operations on numeric operands.

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
++Incrementa++ or ++a
--Decrementa-- or --a

Let's see these operators in action:

csharp
int a = 10;
int b = 3;

Console.WriteLine($"Addition: {a} + {b} = {a + b}"); // Output: Addition: 10 + 3 = 13
Console.WriteLine($"Subtraction: {a} - {b} = {a - b}"); // Output: Subtraction: 10 - 3 = 7
Console.WriteLine($"Multiplication: {a} * {b} = {a * b}"); // Output: Multiplication: 10 * 3 = 30
Console.WriteLine($"Division: {a} / {b} = {a / b}"); // Output: Division: 10 / 3 = 3
Console.WriteLine($"Modulus: {a} % {b} = {a % b}"); // Output: Modulus: 10 % 3 = 1

// Increment and decrement
int c = 5;
Console.WriteLine($"Original value: {c}"); // Output: Original value: 5
Console.WriteLine($"Post-increment: {c++}"); // Output: Post-increment: 5
Console.WriteLine($"After post-increment: {c}"); // Output: After post-increment: 6
Console.WriteLine($"Pre-increment: {++c}"); // Output: Pre-increment: 7

Note on Increment and Decrement Operators

There's an important distinction between pre-increment (++a) and post-increment (a++):

  • Pre-increment (++a) increments the value first, then returns it
  • Post-increment (a++) returns the original value first, then increments it

This same concept applies to the decrement operator (--).

2. Assignment Operators

Assignment operators assign values to variables.

OperatorDescriptionExampleEquivalent to
=Simple assignmenta = ba = b
+=Add and assigna += ba = a + b
-=Subtract and assigna -= ba = a - b
*=Multiply and assigna *= ba = a * b
/=Divide and assigna /= ba = a / b
%=Modulus and assigna %= ba = a % b

Examples of assignment operators:

csharp
int x = 10;
Console.WriteLine($"Initial value: {x}"); // Output: Initial value: 10

x += 5; // Same as x = x + 5
Console.WriteLine($"After x += 5: {x}"); // Output: After x += 5: 15

x -= 3; // Same as x = x - 3
Console.WriteLine($"After x -= 3: {x}"); // Output: After x -= 3: 12

x *= 2; // Same as x = x * 2
Console.WriteLine($"After x *= 2: {x}"); // Output: After x *= 2: 24

x /= 4; // Same as x = x / 4
Console.WriteLine($"After x /= 4: {x}"); // Output: After x /= 4: 6

x %= 4; // Same as x = x % 4
Console.WriteLine($"After x %= 4: {x}"); // Output: After x %= 4: 2

3. Comparison Operators

Comparison operators compare two values and return a boolean result (true or false).

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

Let's see these operators at work:

csharp
int x = 10, y = 5;

Console.WriteLine($"{x} == {y}: {x == y}"); // Output: 10 == 5: False
Console.WriteLine($"{x} != {y}: {x != y}"); // Output: 10 != 5: True
Console.WriteLine($"{x} > {y}: {x > y}"); // Output: 10 > 5: True
Console.WriteLine($"{x} < {y}: {x < y}"); // Output: 10 < 5: False
Console.WriteLine($"{x} >= {y}: {x >= y}"); // Output: 10 >= 5: True
Console.WriteLine($"{x} <= {y}: {x <= y}"); // Output: 10 <= 5: False

// Comparing with the same value
int z = 10;
Console.WriteLine($"{x} == {z}: {x == z}"); // Output: 10 == 10: True

4. Logical Operators

Logical operators are used to combine conditional statements.

OperatorDescriptionExample
&&Logical ANDa && b
||Logical ORa || b
!Logical NOT!a

Here's how logical operators work:

csharp
bool isAdult = true;
bool hasLicense = false;

// Logical AND - both conditions must be true
bool canDrive = isAdult && hasLicense;
Console.WriteLine($"Can drive: {canDrive}"); // Output: Can drive: False

// Logical OR - at least one condition must be true
bool isEligible = isAdult || hasLicense;
Console.WriteLine($"Is eligible: {isEligible}"); // Output: Is eligible: True

// Logical NOT - inverts the value
Console.WriteLine($"Not an adult: {!isAdult}"); // Output: Not an adult: False

5. Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.

OperatorDescriptionExample
&Bitwise ANDa & b
|Bitwise ORa | b
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << 1
>>Right shifta >> 1

Let's see an example:

csharp
int a = 5;  // Binary: 0101
int b = 3; // Binary: 0011

Console.WriteLine($"{a} & {b} = {a & b}"); // Output: 5 & 3 = 1 (Binary: 0001)
Console.WriteLine($"{a} | {b} = {a | b}"); // Output: 5 | 3 = 7 (Binary: 0111)
Console.WriteLine($"{a} ^ {b} = {a ^ b}"); // Output: 5 ^ 3 = 6 (Binary: 0110)
Console.WriteLine($"~{a} = {~a}"); // Output: ~5 = -6 (Binary: 1...1010)
Console.WriteLine($"{a} << 1 = {a << 1}"); // Output: 5 << 1 = 10 (Binary: 1010)
Console.WriteLine($"{a} >> 1 = {a >> 1}"); // Output: 5 >> 1 = 2 (Binary: 0010)

6. Conditional Operators

The conditional operator is a shorthand for the if-else statement.

Ternary Operator

The syntax is: condition ? expression1 : expression2

If the condition is true, expression1 is evaluated; otherwise, expression2 is evaluated.

csharp
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine($"Status: {status}"); // Output: Status: Adult

// Equivalent if-else statement
string statusIfElse;
if (age >= 18)
statusIfElse = "Adult";
else
statusIfElse = "Minor";
Console.WriteLine($"Status (if-else): {statusIfElse}"); // Output: Status (if-else): Adult

Null-coalescing Operator

The null-coalescing operator ?? returns the left-hand operand if it isn't null; otherwise, it returns the right-hand operand.

csharp
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine($"Hello, {displayName}!"); // Output: Hello, Guest!

name = "John";
displayName = name ?? "Guest";
Console.WriteLine($"Hello, {displayName}!"); // Output: Hello, John!

Null-conditional Operator

The null-conditional operator ?. is used to access members of an object only if the object isn't null.

csharp
string text = null;
int? length = text?.Length;
Console.WriteLine($"Length: {length ?? 0}"); // Output: Length: 0

text = "Hello";
length = text?.Length;
Console.WriteLine($"Length: {length}"); // Output: Length: 5

7. Other Important Operators

C# has several other operators that serve various purposes:

typeof Operator

Returns the System.Type object for a type.

csharp
Type stringType = typeof(string);
Console.WriteLine($"Type name: {stringType.Name}"); // Output: Type name: String
Console.WriteLine($"Is value type: {stringType.IsValueType}"); // Output: Is value type: False

sizeof Operator

Returns the size in bytes of a value type.

csharp
unsafe
{
Console.WriteLine($"Size of int: {sizeof(int)} bytes"); // Output: Size of int: 4 bytes
Console.WriteLine($"Size of char: {sizeof(char)} bytes"); // Output: Size of char: 2 bytes
Console.WriteLine($"Size of bool: {sizeof(bool)} bytes"); // Output: Size of bool: 1 bytes
}

is Operator

Checks if an object is compatible with a given type.

csharp
object value = "Hello";
if (value is string)
{
Console.WriteLine("value is a string"); // Output: value is a string
}

value = 42;
if (value is int)
{
Console.WriteLine("value is an integer"); // Output: value is an integer
}

as Operator

Performs type conversion between compatible reference types or nullable types.

csharp
object obj = "Hello, World!";
string message = obj as string;
if (message != null)
{
Console.WriteLine($"Message: {message}"); // Output: Message: Hello, World!
}

obj = 123;
message = obj as string; // Will be null since int is not a string
Console.WriteLine($"Is message null? {message == null}"); // Output: Is message null? True

Operator Precedence

Not all operators are created equal! C# follows an order of precedence when evaluating expressions with multiple operators:

  1. Primary operators (x.y, f(x), a[i], x++, x--)
  2. Unary operators (+, -, !, ~, ++x, --x, (T)x)
  3. Multiplicative operators (*, /, %)
  4. Additive operators (+, -)
  5. Shift operators (<<, >>)
  6. Relational operators (<, >, <=, >=, is, as)
  7. Equality operators (==, !=)
  8. Logical AND (&)
  9. Logical XOR (^)
  10. Logical OR (|)
  11. Conditional AND (&&)
  12. Conditional OR (||)
  13. Null-coalescing operator (??)
  14. Conditional operator (?:)
  15. Assignment operators (=, +=, -=, etc.)

You can use parentheses to override the default precedence and control the order of evaluation.

csharp
int result1 = 5 + 3 * 2;  // Multiplication happens first
Console.WriteLine($"5 + 3 * 2 = {result1}"); // Output: 5 + 3 * 2 = 11

int result2 = (5 + 3) * 2; // Parentheses override precedence
Console.WriteLine($"(5 + 3) * 2 = {result2}"); // Output: (5 + 3) * 2 = 16

Real-world Applications

Example 1: Calculating Discounts in a Shopping Cart

csharp
decimal originalPrice = 100.00m;
bool isDiscountSeason = true;
bool isMember = true;

// Using operators to calculate final price
decimal seasonalDiscount = isDiscountSeason ? 20.00m : 0m;
decimal memberDiscount = isMember ? originalPrice * 0.10m : 0m;
decimal finalPrice = originalPrice - seasonalDiscount - memberDiscount;

Console.WriteLine($"Original price: ${originalPrice}");
Console.WriteLine($"Seasonal discount: ${seasonalDiscount}");
Console.WriteLine($"Member discount: ${memberDiscount}");
Console.WriteLine($"Final price: ${finalPrice}");

/* Output:
Original price: $100.00
Seasonal discount: $20.00
Member discount: $10.00
Final price: $70.00
*/

Example 2: Parsing and Validating User Input

csharp
string userInput = "42";

// Try to parse the input to an integer
bool isValidInteger = int.TryParse(userInput, out int number);

// Using logical operators to validate the input
if (isValidInteger && number >= 0 && number <= 100)
{
Console.WriteLine($"Valid input: {number} is between 0 and 100");
}
else if (isValidInteger && (number < 0 || number > 100))
{
Console.WriteLine($"Invalid range: {number} is not between 0 and 100");
}
else
{
Console.WriteLine($"Invalid input: '{userInput}' is not a valid integer");
}

// Output: Valid input: 42 is between 0 and 100

Example 3: Building a Simple Calculator

csharp
double num1 = 15;
double num2 = 5;
char operation = '*';

double result = operation switch
{
'+' => num1 + num2,
'-' => num1 - num2,
'*' => num1 * num2,
'/' => num2 != 0 ? num1 / num2 : throw new DivideByZeroException("Cannot divide by zero"),
'%' => num2 != 0 ? num1 % num2 : throw new DivideByZeroException("Cannot divide by zero"),
_ => throw new ArgumentException($"Unsupported operation: {operation}")
};

Console.WriteLine($"{num1} {operation} {num2} = {result}");
// Output: 15 * 5 = 75

Summary

C# operators are essential tools for manipulating data and controlling program flow. In this guide, we've covered:

  • Arithmetic operators for mathematical operations
  • Assignment operators for assigning values
  • Comparison operators for comparing values
  • Logical operators for combining conditions
  • Bitwise operators for bit-level operations
  • Conditional operators for making decisions
  • Special operators like typeof, sizeof, is, and as
  • Operator precedence and the use of parentheses
  • Real-world applications of operators

Understanding how these operators work and when to use them will help you write more efficient, readable, and powerful C# code.

Further Learning

Exercises

  1. Create a simple BMI (Body Mass Index) calculator using arithmetic operators
  2. Write a program that determines whether a year is a leap year using logical operators
  3. Implement a simple temperature converter between Celsius, Fahrenheit, and Kelvin
  4. Create a grade calculator that assigns letter grades based on numerical scores using conditional operators
  5. Build a binary number converter that uses bitwise operators to manipulate bits

Additional Resources

Remember, the best way to master operators is through practice. Try to use different operators in your code and experiment with their behavior to gain a deeper understanding of how they work.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)