Beginner 14 min read

Operators

Arithmetic, comparison, logical, bitwise, null-coalescing.

Operators in C#

Operators are an essential part of C# programming because they allow you to perform calculations, compare values, evaluate conditions, and make decisions in your application.

Whether you are calculating an order total, validating user input, checking permissions, or handling nullable data in an ASP.NET Core Web API, operators help you express the logic your application needs.

C# provides several categories of operators, including arithmetic, comparison, logical, bitwise, and null-coalescing operators. Understanding when and how to use each category will help you write cleaner code and avoid common programming mistakes.

Prerequisite: Understand C# Data Types First

Before learning operators, make sure you understand the data types on which they operate.

If you haven't read our previous article, start here: Data Types and Type System in C#: Value Types, Reference Types, and Conversion.

That article explains how C# handles integers, Boolean values, reference types, and type conversions. These concepts are important because the result of an operator depends on the types of its operands.

1. What Are Operators in C#?

An operator is a symbol or keyword that performs an operation on one or more operands.

For example:

int firstNumber = 10;
int secondNumber = 5;

int result = firstNumber + secondNumber;

Console.WriteLine(result);

Output:

15

In this example:

  • firstNumber and secondNumber are operands.
  • + is the arithmetic operator.
  • result stores the calculated value.

Operators can work with numbers, strings, Boolean expressions, objects, and other supported types.

Main Categories of C# Operators

CategoryPurposeExamples
ArithmeticPerform mathematical calculations+, -, *, /, %
ComparisonCompare two values==, !=, >, <, >=, <=
LogicalCombine or reverse Boolean conditions&&, `
BitwisePerform operations on individual bits&, `
AssignmentAssign or update values=, +=, -=, *=
Increment and decrementIncrease or decrease a value by one++, --
Null-coalescingProvide a fallback for a null value??, ??=
ConditionalSelect a value based on a condition?:

Let's explore the most important operators with practical examples.

2. Arithmetic Operators in C#

Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, and division.

They are commonly used in financial calculations, order processing, reporting, and business logic.

Common Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
%Modulus10 % 31

Practical Example

int firstNumber = 10;
int secondNumber = 3;

Console.WriteLine(firstNumber + secondNumber);
Console.WriteLine(firstNumber - secondNumber);
Console.WriteLine(firstNumber * secondNumber);
Console.WriteLine(firstNumber / secondNumber);
Console.WriteLine(firstNumber % secondNumber);

Output:

13
7
30
3
1

Notice that dividing two integers produces an integer result. The fractional part is discarded.

For example:

int result = 10 / 3;

Console.WriteLine(result);

Output:

3

If you need a fractional result, use a suitable numeric type.

double result = 10.0 / 3.0;

Console.WriteLine(result);

Output:

3.3333333333333335

Understanding the Modulus Operator

The modulus operator % returns the remainder after division.

One common use is checking whether a number is even or odd.

int number = 12;

if (number % 2 == 0)
{
    Console.WriteLine("Even number");
}
else
{
    Console.WriteLine("Odd number");
}

Output:

Even number

This technique is useful for validation, alternating operations, and processing items in groups.

Important: Integer division by zero throws a DivideByZeroException. Always ensure the divisor is valid when its value can be zero.

3. Comparison Operators in C#

Comparison operators compare two values and return a Boolean result: true or false.

They are frequently used in if statements, loops, validation rules, and filtering conditions.

Common Comparison Operators

OperatorMeaningExampleResult
==Equal to10 == 10true
!=Not equal to10 != 5true
>Greater than10 > 5true
<Less than10 < 5false
>=Greater than or equal to10 >= 10true
<=Less than or equal to5 <= 10true

Practical Example: Age Validation

int age = 22;

if (age >= 18)
{
    Console.WriteLine("Eligible to register");
}
else
{
    Console.WriteLine("Not eligible to register");
}

Output:

Eligible to register

The expression age >= 18 evaluates to true, so the first branch executes.

Difference Between = and ==

This is a common beginner mistake.

  • = assigns a value.
  • == compares two values for equality.
int age = 25;

bool isTwentyFive = age == 25;

Console.WriteLine(isTwentyFive);

Output:

True

Understanding this distinction is important when writing conditions and debugging unexpected results.

4. Logical Operators in C#

Logical operators combine or reverse Boolean expressions.

They are especially useful when a business rule depends on more than one condition.

C# provides three common conditional logical operators:

OperatorMeaningExample
&&Logical ANDage >= 18 && hasId
``
!Logical NOT!isActive

Logical AND (&&)

The AND operator returns true only when both conditions are true.

int age = 25;
bool hasValidId = true;

if (age >= 18 && hasValidId)
{
    Console.WriteLine("Access granted");
}

Output:

Access granted

Both conditions must be satisfied for the message to appear.

Logical OR (||)

The OR operator returns true when at least one condition is true.

bool isAdmin = false;
bool isManager = true;

if (isAdmin || isManager)
{
    Console.WriteLine("Authorized to access the report");
}

Output:

Authorized to access the report

This is useful when multiple roles or conditions can authorize the same operation.

Logical NOT (!)

The NOT operator reverses a Boolean value.

bool isActive = false;

if (!isActive)
{
    Console.WriteLine("Account is inactive");
}

Output:

Account is inactive

Understanding Short-Circuit Evaluation

The && and || operators use short-circuit evaluation.

With &&, if the first condition is false, C# does not evaluate the second condition because the complete expression cannot be true.

With ||, if the first condition is true, C# does not evaluate the second condition because the complete expression is already true.

Consider this example:

string? name = null;

if (name != null && name.Length > 0)
{
    Console.WriteLine("Name is available");
}
else
{
    Console.WriteLine("Name is missing");
}

Output:

Name is missing

Because name != null is false, the second condition is not evaluated. This prevents an attempt to access Length on a null reference.

Interview tip: Understand why && can protect a later expression from evaluation. This behavior is frequently useful in null checks and validation logic.

5. Bitwise Operators in C#

Bitwise operators operate on the individual bits of integral values.

Unlike logical operators, which work with Boolean conditions, bitwise operators manipulate the binary representation of their operands.

The most common bitwise operators are:

OperatorNamePurpose
&Bitwise ANDSets a bit when both corresponding bits are set
``Bitwise OR
^Bitwise XORSets a bit when corresponding bits differ
~Bitwise complementInverts the bits
<<Left shiftShifts bits to the left
>>Right shiftShifts bits to the right

Bitwise AND Example

Consider the following code:

int firstNumber = 5;
int secondNumber = 3;

Console.WriteLine(firstNumber & secondNumber);

Output:

1

The numbers have these binary representations:

5 = 0101
3 = 0011
---------
    0001

Only the bits set to 1 in both numbers remain set in the result.

Bitwise OR Example

int firstNumber = 5;
int secondNumber = 3;

Console.WriteLine(firstNumber | secondNumber);

Output:

7

Binary calculation:

5 = 0101
3 = 0011
---------
    0111

The result is 7.

Bitwise XOR Example

The XOR operator returns 1 for each bit position where the corresponding bits differ.

int firstNumber = 5;
int secondNumber = 3;

Console.WriteLine(firstNumber ^ secondNumber);

Output:

6

Binary calculation:

5 = 0101
3 = 0011
---------
    0110

Logical AND vs Bitwise AND

This distinction is important.

bool firstCondition = true;
bool secondCondition = false;

Console.WriteLine(firstCondition && secondCondition);

Output:

False

Here, && combines Boolean conditions and uses short-circuit evaluation.

By contrast:

int firstNumber = 5;
int secondNumber = 3;

Console.WriteLine(firstNumber & secondNumber);

Output:

1

Here, & performs a bitwise operation on integers.

The & operator can also be used with Boolean values, but unlike &&, it evaluates both operands.

When Are Bitwise Operators Useful?

Bitwise operations are useful for:

  • Managing permission flags.
  • Setting and checking individual bits.
  • Working with binary protocols.
  • Handling low-level data representations.
  • Implementing efficient flag-based configurations.

For example, C# supports the [Flags] attribute for enums representing combinations of flags.

[Flags]
public enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4
}

You can combine permissions using the bitwise OR operator.

Permissions userPermissions =
    Permissions.Read | Permissions.Write;

Console.WriteLine(userPermissions);

Output:

Read, Write

The user has both read and write permissions.

6. Null-Coalescing Operators in C#

In C#, a variable may sometimes contain null instead of an actual value or object reference.

Null-coalescing operators help you handle such situations by providing a fallback value or assigning a value only when the current value is null.

The two main null-coalescing operators are:

  • ?? — null-coalescing operator.
  • ??= — null-coalescing assignment operator.

The Null-Coalescing Operator (??)

The ?? operator returns the left-hand operand when it is not null. Otherwise, it returns the right-hand operand.

string? userName = null;

string displayName = userName ?? "Guest";

Console.WriteLine(displayName);

Output:

Guest

Because userName is null, the expression returns "Guest".

Now consider the same example with a non-null value.

string? userName = "Shreya";

string displayName = userName ?? "Guest";

Console.WriteLine(displayName);

Output:

Shreya

Since userName is not null, the fallback value is not used.

Practical Example in ASP.NET Core

Suppose an application receives an optional display name from a request or another data source.

public string GetDisplayName(string? name)
{
    return name ?? "Guest";
}

This method returns the supplied name when available and uses "Guest" when the argument is null.

This pattern is helpful when working with optional request properties, nullable database values, and application defaults.

The Null-Coalescing Assignment Operator (??=)

The ??= operator assigns a value only when the left-hand operand is null.

string? userName = null;

userName ??= "Guest";

Console.WriteLine(userName);

Output:

Guest

If userName already contains a value, the assignment does not replace it.

string? userName = "Shreya";

userName ??= "Guest";

Console.WriteLine(userName);

Output:

Shreya

This is useful when you want to initialize an optional value only if it has not already been provided.

Important: The ?? operator does not treat an empty string or zero as null. It checks only whether the left-hand operand is null.

7. Assignment Operators in C#

Assignment operators assign values to variables. In addition to the basic assignment operator, C# provides compound assignment operators that combine an operation with an assignment.

OperatorExampleEquivalent Expression
=number = 10;Assigns 10
+=number += 5;number = number + 5;
-=number -= 3;number = number - 3;
*=number *= 2;number = number * 2;
/=number /= 2;number = number / 2;
%=number %= 3;number = number % 3;

Practical Example

int total = 100;

total += 50;
total -= 20;
total *= 2;

Console.WriteLine(total);

Output:

260

The value changes as follows:

  1. 100 + 50 = 150
  2. 150 - 20 = 130
  3. 130 * 2 = 260

Compound assignment operators can make simple updates more concise and readable.

8. Increment and Decrement Operators

The increment operator ++ increases a variable's value by one. The decrement operator -- decreases it by one.

int count = 5;

count++;

Console.WriteLine(count);

count--;

Console.WriteLine(count);

Output:

6
5

Difference Between Prefix and Postfix

C# supports both prefix and postfix forms.

  • ++count increments the value before the expression is evaluated.
  • count++ evaluates to the current value before incrementing the variable.

For example:

int count = 5;

Console.WriteLine(count++);
Console.WriteLine(count);

Output:

5
6

Now consider the prefix version:

int count = 5;

Console.WriteLine(++count);
Console.WriteLine(count);

Output:

6
6

The distinction matters when an increment or decrement appears inside a larger expression.

For clearer application code, avoid unnecessarily complex expressions that combine multiple increments or decrements.

9. Conditional Operator (?:)

The conditional operator provides a concise way to select one of two expressions based on a Boolean condition.

It is often called the ternary operator because it takes three operands.

int age = 20;

string message = age >= 18
    ? "Adult"
    : "Minor";

Console.WriteLine(message);

Output:

Adult

The expression checks whether age >= 18. If the condition is true, it selects "Adult"; otherwise, it selects "Minor".

This is useful for simple conditional assignments.

For complicated business rules, a regular if-else statement is usually easier to read.

10. Operator Precedence in C#

When an expression contains multiple operators, C# follows operator precedence rules to determine which operations are performed first.

Consider this example:

int result = 10 + 5 * 2;

Console.WriteLine(result);

Output:

20

Multiplication has higher precedence than addition, so the multiplication happens first.

The expression is evaluated as:

10 + (5 * 2)
10 + 10
20

If you want addition to happen first, use parentheses.

int result = (10 + 5) * 2;

Console.WriteLine(result);

Output:

30

Parentheses make the intended evaluation order explicit and often improve readability.

Best practice: When an expression contains several operators, use parentheses when they make your intention clearer rather than relying on readers to remember precedence rules.

11. Common Mistakes to Avoid

Mistake 1: Confusing Assignment and Comparison

int age = 25;

bool result = age == 25;

Use = to assign a value and == to compare values.

Mistake 2: Forgetting Integer Division

int result = 7 / 2;

Console.WriteLine(result);

Output:

3

Use floating-point or decimal arithmetic when the calculation requires a fractional result.

Mistake 3: Using & Instead of &&

When you want short-circuit evaluation for Boolean conditions, use && rather than &.

The bitwise operator & evaluates both Boolean operands.

Mistake 4: Assuming ?? Handles Empty Strings

string? name = "";

string result = name ?? "Guest";

Console.WriteLine(result);

The output is an empty string because name is not null.

If you want to treat null, empty, and whitespace-only strings as missing, use an appropriate string validation method, such as string.IsNullOrWhiteSpace().

Mistake 5: Ignoring Operator Precedence

When mixing arithmetic, comparison, and logical operators, use parentheses to communicate the intended evaluation order.

Mistake 6: Forgetting That Explicit Numeric Conversions Can Lose Information

Casting a floating-point number to an integer discards the fractional component. Choose an appropriate conversion strategy for the problem you are solving.

12. Frequently Asked Questions

1. What are operators in C#?

Operators are symbols or keywords that perform operations on one or more operands. They support arithmetic calculations, comparisons, logical decisions, bitwise operations, assignments, and null handling.

2. What are the main types of operators in C#?

Common categories include arithmetic, comparison, logical, bitwise, assignment, increment and decrement, conditional, and null-coalescing operators.

3. What is the difference between == and = in C#?

The = operator assigns a value to a variable, while == checks whether two values are equal according to the applicable equality operator.

4. What is the difference between && and & in C#?

The && operator performs conditional logical AND with short-circuit evaluation. The & operator can perform bitwise AND on integral values and non-short-circuit logical AND on Boolean values.

5. What does the modulus operator % do in C#?

The modulus operator returns the remainder after division. It is commonly used to check whether a number is even or odd or to perform other remainder-based calculations.

6. What is the null-coalescing operator in C#?

The ?? operator returns the left-hand operand when it is not null; otherwise, it returns the right-hand operand. It provides a convenient way to specify a fallback value.

7. What is the difference between ?? and ??= in C#?

The ?? operator evaluates to a fallback value when its left operand is null. The ??= operator assigns a value to its left operand only when that operand is null.

8. What is the difference between prefix and postfix increment?

Prefix increment, ++count, increments the variable before the expression's value is produced. Postfix increment, count++, produces the original value before incrementing the variable.

9. What are bitwise operators used for in C#?

Bitwise operators manipulate individual bits in integral values. They are useful for flag combinations, permission masks, binary data processing, and low-level operations.

10. Why is operator precedence important in C#?

Operator precedence determines the order in which operators within an expression are evaluated. Understanding precedence and using parentheses helps prevent incorrect calculations and makes expressions easier to read.


Key Takeaways

C# operators help you express calculations, comparisons, business rules, and null-handling logic.

  • Use arithmetic operators for mathematical calculations.
  • Use comparison operators to evaluate relationships between values.
  • Use logical operators to combine Boolean conditions.
  • Use bitwise operators when working with individual bits or flag combinations.
  • Use ?? and ??= to handle nullable values and provide defaults.
  • Understand assignment, increment, decrement, and conditional operators.
  • Use parentheses to make complex expressions easier to understand.

Next step: Create a console application and practise each operator category with sample values. Then combine comparison, logical, and null-coalescing operators to implement simple validation rules similar to those used in real ASP.NET Core applications.

Official Microsoft Documentation

For deeper technical explanations, explore these official Microsoft resources:


Last updated 10/27/2026

Your notes

Sign in to save personal notes on this topic — they'll sync across your devices.

Was this tutorial helpful?

Help us create more free learning resources. Learn more

Make a Donation