Paramclasses Academy - Blog

Tutorials Details

←
Post 5 of 30
→

What is C# Operators and Expressions ?

What is C# Operators and Expressions ?

October 24, 2026

Introduction

Operators are one of the fundamental concepts of C# programming. They allow developers to perform calculations, compare values, assign data to variables, combine conditions, and control program logic.

Whether you are building a console application, a web application with ASP.NET Core, or a desktop application, you will use operators in almost every C# program.

For example:

int a = 10;
int b = 5;

int sum = a + b;

Console.WriteLine(sum);

Output:

15

In this example, + is an arithmetic operator that adds two values.

In this tutorial, you will learn the different types of C# operators, how expressions work, operator precedence, practical examples, common mistakes, and programming exercises.

1. What Are Operators in C#?

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

An operand is the value or variable on which an operator operates.

For example:

int result = 10 + 20;

In this statement:

  • 10 and 20 are operands.

  • + is the operator.

  • 10 + 20 is an expression.

  • result stores the calculated value.

C# provides several categories of operators, including arithmetic, assignment, comparison, logical, bitwise, unary, conditional, and null-coalescing operators.

2. Types of Operators in C#

The main categories of C# operators are:

Operator Category Purpose
Arithmetic Perform mathematical calculations
Assignment Assign values to variables
Comparison Compare two values
Logical Combine or reverse Boolean conditions
Unary Operate on a single operand
Increment and Decrement Increase or decrease a value
Bitwise Perform operations on individual bits
Conditional Select a value based on a condition
Null-Coalescing Provide a fallback for null values
Type Operators Check or work with types
Shift Shift bits left or right

Let's explore each category with examples.

3. Arithmetic Operators in C#

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

Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Remainder 10 % 3 1

Addition Operator

The addition operator adds two values.

int a = 10;
int b = 20;

int result = a + b;

Console.WriteLine(result);

Output:

30

Subtraction Operator

The subtraction operator calculates the difference between two values.

int a = 50;
int b = 20;

Console.WriteLine(a - b);

Output:

30

Multiplication Operator

The multiplication operator multiplies two values.

int price = 100;
int quantity = 5;

int total = price * quantity;

Console.WriteLine(total);

Output:

500

Division Operator

The division operator divides one value by another.

int a = 20;
int b = 4;

Console.WriteLine(a / b);

Output:

5

Important: When both operands are integers, C# performs integer division and discards the fractional part.

Console.WriteLine(10 / 3);

Output:

3

To obtain a fractional result, use a floating-point or decimal operand.

double result = 10.0 / 3;

Console.WriteLine(result);

Output:

3.3333333333333335

The exact displayed representation can depend on the numeric type and formatting.

Modulus Operator

The modulus operator % returns the remainder after division.

int result = 17 % 5;

Console.WriteLine(result);

Output:

2

The modulus operator is commonly used to determine whether a number is even or odd.

int number = 8;

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

Output:

Even number

An integer remainder of zero indicates that the number is divisible by two.

4. Assignment Operators in C#

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

int number = 10;
Console.WriteLine(number);

Output:

10

C# also supports compound assignment operators.

Operator Equivalent Expression
+= x = x + value
-= x = x - value
*= x = x * value
/= x = x / value
%= x = x % value
&= x = x & value
` =` `x = x value`
^= x = x ^ value
<<= x = x << value
>>= x = x >> value

Example of Compound Assignment

int number = 10;

number += 5;
Console.WriteLine(number);

number -= 3;
Console.WriteLine(number);

number *= 2;
Console.WriteLine(number);

number /= 4;
Console.WriteLine(number);

Output:

15
12
24
6

Compound assignment makes code shorter and easier to read when updating variables.

5. Comparison Operators in C#

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

Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Example

int age = 20;

Console.WriteLine(age == 20);
Console.WriteLine(age > 18);
Console.WriteLine(age < 18);
Console.WriteLine(age != 20);

Output:

True
True
False
False

Comparison operators are frequently used in if, else, and loop conditions.

int marks = 75;

if (marks >= 40)
{
    Console.WriteLine("You passed the exam.");
}
else
{
    Console.WriteLine("You failed the exam.");
}

Output:

You passed the exam.

Common mistake: = assigns a value, whereas == compares two values.

int number = 10;          // Assignment
bool isTen = number == 10; // Comparison

6. Logical Operators in C#

Logical operators combine or reverse Boolean conditions.

Operator Name Meaning
&& Logical AND True when both conditions are true
`   ` Logical OR True when at least one condition is true
! Logical NOT Reverses a Boolean value

Logical AND (&&)

Both conditions must be true for the complete expression to be true.

int age = 25;
bool hasLicense = true;

if (age >= 18 && hasLicense)
{
    Console.WriteLine("Eligible to drive.");
}

Output:

Eligible to drive.

Logical OR (||)

At least one condition must be true.

bool isWeekend = false;
bool isHoliday = true;

if (isWeekend || isHoliday)
{
    Console.WriteLine("No regular work today.");
}

Output:

No regular work today.

Logical NOT (!)

The NOT operator reverses a Boolean value.

bool isLoggedIn = false;

Console.WriteLine(!isLoggedIn);

Output:

True

Short-Circuit Evaluation

C# uses short-circuit evaluation with && and ||.

For &&, if the first condition is false, the second condition does not need to be evaluated. For ||, if the first condition is true, the second condition does not need to be evaluated.

int number = 0;

if (number != 0 && 100 / number > 1)
{
    Console.WriteLine("Condition is true.");
}
else
{
    Console.WriteLine("Condition is false.");
}

Output:

Condition is false.

Because number != 0 is false, C# does not evaluate 100 / number. This avoids division by zero in this example.

7. Increment and Decrement Operators

Increment and decrement operators change a variable's value by one.

Operator Meaning
++ Increase by one
-- Decrease by one

Increment Example

int number = 5;

number++;

Console.WriteLine(number);

Output:

6

Decrement Example

int number = 5;

number--;

Console.WriteLine(number);

Output:

4

Prefix vs. Postfix

The position of the operator matters when the expression's value is used.

Prefix increment (++x) increments the variable before producing its value.

int x = 5;

Console.WriteLine(++x);

Output:

6

Postfix increment (x++) produces the original value first, then increments the variable.

int x = 5;

Console.WriteLine(x++);
Console.WriteLine(x);

Output:

5
6

The same distinction applies to prefix and postfix decrement.

8. Unary Operators in C#

A unary operator works with a single operand.

Common examples include:

Operator Purpose
+ Unary plus
- Negation
! Logical NOT
~ Bitwise complement
++ Increment
-- Decrement

Example:

int number = 10;

Console.WriteLine(+number);
Console.WriteLine(-number);

Output:

10
-10

Unary plus preserves the numeric value, while unary minus reverses its sign.

9. Bitwise Operators in C#

Bitwise operators work on the individual bits of integral numeric values.

They are useful in scenarios such as flags, low-level programming, permissions, and performance-sensitive operations.

Operator Name
& Bitwise AND
` ` Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Left shift
>> Right shift

Bitwise AND

A bit is set in the result only when the corresponding bits in both operands are set.

int a = 6; // Binary: 0110
int b = 3; // Binary: 0011

Console.WriteLine(a & b);

Output:

2

The result is binary 0010, which represents decimal 2.

Bitwise OR

A result bit is set when at least one corresponding operand bit is set.

int a = 6;
int b = 3;

Console.WriteLine(a | b);

Output:

7

Bitwise XOR

A result bit is set when the corresponding bits differ.

int a = 6;
int b = 3;

Console.WriteLine(a ^ b);

Output:

5

Left Shift

The left-shift operator moves bits toward the left.

int number = 4;

Console.WriteLine(number << 1);

Output:

8

Right Shift

The right-shift operator moves bits toward the right.

int number = 8;

Console.WriteLine(number >> 1);

Output:

4

Bit shifting should be used with an understanding of the numeric type, sign, and overflow behavior. Do not assume every shift is interchangeable with multiplication or division in all situations.

10. Conditional Operator (?:) in C#

The conditional operator is a compact alternative to a simple if-else expression.

Syntax:

condition ? valueIfTrue : valueIfFalse;

Example

int age = 20;

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

Console.WriteLine(result);

Output:

Adult

If the condition is true, the expression produces "Adult". Otherwise, it produces "Minor".

A conditional operator is useful for simple decisions. For complex branching logic, a conventional if-else statement is often easier to understand.

11. Null-Coalescing Operators in C#

C# provides operators that help handle nullable values and null references.

Null-Coalescing Operator (??)

The ?? operator returns the left operand if it is not null; otherwise, it returns the right operand.

string? username = null;

string displayName = username ?? "Guest";

Console.WriteLine(displayName);

Output:

Guest

The string? annotation indicates that the variable may contain null when nullable reference types are enabled.

Null-Coalescing Assignment (??=)

The ??= operator assigns a fallback value only if the variable is null.

string? username = null;

username ??= "Guest";

Console.WriteLine(username);

Output:

Guest

If username already contains a non-null value, ??= leaves it unchanged.

Null-Conditional Operator (?.)

The null-conditional operator helps access a member only when the value to its left is not null.

string? username = null;

int? length = username?.Length;

Console.WriteLine(length);

Output:


 

The output is blank because length is null and Console.WriteLine displays no visible characters for a null value.

These operators are particularly useful when working with optional user input, API responses, and database values.

12. Type Operators in C#

Type-related operators and expressions help you check or work with data types.

is Operator

The is operator checks whether a value matches a specified type or pattern.

object value = "Hello";

if (value is string)
{
    Console.WriteLine("The value is a string.");
}

Output:

The value is a string.

You can also use pattern matching to declare a variable when the value matches a type.

object value = "Hello";

if (value is string text)
{
    Console.WriteLine(text.Length);
}

Output:

5

as Operator

The as operator attempts a reference or nullable conversion and returns null if the conversion fails.

object value = "Hello";

string? text = value as string;

Console.WriteLine(text);

Output:

Hello

The as operator does not replace all explicit casts and is not used for ordinary numeric conversions.

typeof Operator

The typeof operator obtains the System.Type object for a type known at compile time.

Console.WriteLine(typeof(int));
Console.WriteLine(typeof(string));

Output:

System.Int32
System.String

13. Operator Precedence in C#

Operator precedence determines which operators are evaluated first in an expression.

For example:

int result = 10 + 5 * 2;

Console.WriteLine(result);

Output:

20

Multiplication has higher precedence than addition, so 5 * 2 is evaluated first.

To change the evaluation order, use parentheses.

int result = (10 + 5) * 2;

Console.WriteLine(result);

Output:

30

Common Operator Precedence Order

The following table gives a simplified overview from higher to lower precedence. Operators within the same category may have additional associativity rules.

Priority Operators or Categories
Highest Parentheses and member access
High Unary operators, prefix increment and decrement
High Multiplication, division, remainder
Medium Addition and subtraction
Medium Shift operators
Medium Relational and type-testing operators
Lower Equality operators
Lower Bitwise AND, XOR, and OR
Lower Logical AND (&&)
Lower Logical OR (`   `)
Low Null-coalescing (??)
Low Conditional (?:)
Assignment level Assignment and compound assignment

When an expression becomes difficult to read, use parentheses to make the intended order explicit.

14. Expressions in C#

An expression is a combination of literals, variables, operators, and method calls that produces a value.

Examples:

10 + 20
price * quantity
age >= 18
isLoggedIn && hasPermission

Expressions can be used to assign values, control conditions, return results, or pass arguments to methods.

Arithmetic Expression

int total = 100 + 50;
Console.WriteLine(total);

Output:

150

Boolean Expression

int age = 22;

bool isAdult = age >= 18;

Console.WriteLine(isAdult);

Output:

True

Compound Expression

int a = 10;
int b = 5;
int c = 2;

int result = (a + b) * c;

Console.WriteLine(result);

Output:

30

Expressions are essential because they combine data and operations to produce the values used by a program.

15. Practical Example: Simple Calculator in C#

Let's create a simple calculator using arithmetic operators.

using System;

class Program
{
    static void Main()
    {
        int a = 20;
        int b = 5;

        Console.WriteLine("Addition: " + (a + b));
        Console.WriteLine("Subtraction: " + (a - b));
        Console.WriteLine("Multiplication: " + (a * b));
        Console.WriteLine("Division: " + (a / b));
        Console.WriteLine("Remainder: " + (a % b));
    }
}

Output:

Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4
Remainder: 0

This program demonstrates five arithmetic operations using two integer variables.

For a more interactive calculator, you could accept input from the user, ask which operation they want to perform, and validate the divisor before division.

16. Common Mistakes When Using C# Operators

Mistake 1: Confusing = and ==

Incorrect understanding:

int number = 10;
bool result = number == 10;

The first statement assigns 10 to number. The second compares number with 10 and stores a Boolean result.

Remember:

  • = means assignment.

  • == means equality comparison.

Mistake 2: Unexpected Integer Division

double result = 5 / 2;

Console.WriteLine(result);

Output:

2

Although the result variable is a double, the division happens between two integers first.

Correct version:

double result = 5.0 / 2;

Console.WriteLine(result);

Output:

2.5

Mistake 3: Dividing by Zero

Integer division by zero throws a DivideByZeroException.

int a = 10;
int b = 0;

// int result = a / b; // Throws DivideByZeroException

Check the divisor before performing the operation.

int a = 10;
int b = 0;

if (b != 0)
{
    Console.WriteLine(a / b);
}
else
{
    Console.WriteLine("Cannot divide by zero.");
}

Mistake 4: Ignoring Operator Precedence

int result = 2 + 3 * 4;
Console.WriteLine(result);

The result is 14, not 20, because multiplication is evaluated first.

Use (2 + 3) * 4 if the intended result is 20.

Mistake 5: Confusing && and &

For Boolean values, && performs logical AND with short-circuit evaluation, while & evaluates both Boolean operands.

bool first = false;
bool second = true;

Console.WriteLine(first && second);
Console.WriteLine(first & second);

Both expressions produce False, but their evaluation behavior differs. The & operator also has a bitwise meaning for integral operands.

Mistake 6: Overusing Increment Operators in Complex Expressions

Expressions such as x++ + ++x can be difficult to reason about. Prefer separate statements when clarity matters.

int x = 5;

x++;
x++;

Console.WriteLine(x);

Output:

7

Clear code is easier to debug and maintain.

17. Best Practices for Using Operators

Follow these practices when writing C# code:

  1. Use parentheses when the intended evaluation order might not be obvious.

  2. Use descriptive variable names so expressions are easy to understand.

  3. Validate divisors before integer division when zero is possible.

  4. Use && and || when short-circuit logical evaluation is intended.

  5. Avoid complex expressions with multiple increment or decrement operations.

  6. Choose suitable numeric types for your calculations.

  7. Use the null-coalescing operators when a clear fallback value is appropriate.

  8. Keep conditions simple enough to read and test.

  9. Use bitwise operators only when bit-level behavior is intended.

  10. Test boundary cases, such as zero, negative values, and maximum or minimum numeric values.

18. Practice Exercise

Create a C# program that calculates a student's result using operators.

Requirements

  • Declare variables for a student's name and marks in three subjects.

  • Calculate the total marks.

  • Calculate the average using floating-point division.

  • Check whether the student passed, assuming at least 40 marks in every subject.

  • Check whether the average is at least 75.

  • Display the student's name, total, average, and pass status.

Sample Solution

using System;

class Program
{
    static void Main()
    {
        string studentName = "Rahul";

        int subject1 = 80;
        int subject2 = 75;
        int subject3 = 90;

        int total = subject1 + subject2 + subject3;

        double average = total / 3.0;

        bool passed =
            subject1 >= 40 &&
            subject2 >= 40 &&
            subject3 >= 40;

        bool highAverage = average >= 75;

        Console.WriteLine("Student: " + studentName);
        Console.WriteLine("Total: " + total);
        Console.WriteLine("Average: " + average);
        Console.WriteLine("Passed: " + passed);
        Console.WriteLine("Average is at least 75: " + highAverage);
    }
}

Output:

Student: Rahul
Total: 245
Average: 81.66666666666667
Passed: True
Average is at least 75: True

This exercise combines arithmetic, comparison, logical, and assignment operations in one program.

19. Frequently Asked Questions (FAQs)

1. What are operators in C#?

Operators are symbols or keywords that perform operations on values and variables. Examples include +, -, *, /, ==, and &&.

2. What is the difference between an operator and an operand?

An operator performs an operation, while operands are the values or variables on which the operator works. In 10 + 5, + is the operator and 10 and 5 are operands.

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

= assigns a value to a variable. == checks whether two values are equal and produces a Boolean result.

4. What is the difference between && and ||?

&& returns true only when both Boolean operands are true. || returns true when at least one operand is true. Both operators support short-circuit evaluation.

5. What is the modulus operator in C#?

The modulus operator % returns the remainder of a division. It is commonly used for divisibility checks and even-or-odd tests.

6. What is operator precedence?

Operator precedence defines which operators are evaluated first in an expression. Parentheses can be used to make the intended order explicit.

7. What is the conditional operator in C#?

The conditional operator ?: selects one of two expressions based on a Boolean condition. It is a concise alternative for simple conditional assignments.

8. What is the difference between ++x and x++?

++x increments the variable before producing the expression's value. x++ produces the original value and then increments the variable.

9. What are null-coalescing operators?

The ?? operator returns a fallback when its left operand is null, while ??= assigns a fallback to a variable only when that variable is null.

10. Why does 5 / 2 return 2 in C#?

Both operands are integers, so C# performs integer division and discards the fractional part. Use 5.0 / 2 or another suitable floating-point expression to obtain 2.5.

20. Quiz: Test Your Knowledge

Question 1: What is the output of 10 % 3?

A. 3
B. 1
C. 0
D. 10

Question 2: Which operator checks whether two values are equal?

A. =
B. !=
C. ==
D. >=

Question 3: What is the output of 2 + 3 * 4?

A. 20
B. 14
C. 24
D. 9

Question 4: Which operator performs logical AND with short-circuit evaluation?

A. &
B. &&
C. ||
D. !

Question 5: What is the output of this code?

int x = 5;
Console.WriteLine(x++);
Console.WriteLine(x);

A. 6 then 6
B. 5 then 6
C. 5 then 5
D. 6 then 5

Question 6: Which operator provides a fallback value when the left operand is null?

A. ?.
B. ??
C. ==
D. &&

Quiz Answers

  1. B — 1

  2. C — ==

  3. B — 14

  4. B — &&

  5. B — 5 then 6

  6. B — ??

Conclusion

C# operators are essential tools for performing calculations, comparing values, evaluating conditions, and handling null values. Understanding arithmetic, assignment, comparison, logical, unary, bitwise, conditional, and null-coalescing operators will help you write clearer and more reliable C# programs.

Practice using these operators in small programs before moving to more advanced topics. Pay special attention to integer division, short-circuit evaluation, and operator precedence because these concepts frequently affect program behavior.

←
Post 5 of 30
→