Paramclasses Academy - Blog

Tutorials Details

←
Post 7 of 30
→

What is C# Conditional Statements: If-Else, Switch and Pattern Matching ?

What is C# Conditional Statements: If-Else, Switch and Pattern Matching ?

October 24, 2026

Introduction

Conditional statements are an essential part of C# programming. They allow a program to make decisions and execute different blocks of code depending on whether certain conditions are true or false.

For example, an application may need to check whether a student has passed an exam, whether a user is old enough to register, or whether an order qualifies for a discount.

Consider the following example:

int age = 20;

if (age >= 18)
{
    Console.WriteLine("You are eligible to vote.");
}

Output:

You are eligible to vote.

In this example, the program checks whether age is greater than or equal to 18. Because the condition is true, the message is displayed.

C# provides several ways to implement conditional logic, including if, if-else, else-if, switch, and pattern matching.

In this tutorial, you will learn how these statements work, when to use each one, and how to apply them in practical programs.

1. What Are Conditional Statements in C#?

Conditional statements control the flow of a program by evaluating conditions and choosing which code to execute.

A condition generally evaluates to a Boolean value: true or false.

For example:

int marks = 75;

bool passed = marks >= 40;

Console.WriteLine(passed);

Output:

True

The expression marks >= 40 evaluates to true because marks contains 75.

The main conditional constructs covered in this tutorial are:

Statement or Feature Purpose
if Executes code when a condition is true
if-else Chooses between two alternatives
else-if Checks multiple conditions in sequence
Nested if Places a conditional statement inside another
switch Selects a branch based on a value or pattern
Pattern matching Checks types, values, and other patterns
Conditional operator ?: Produces one of two values based on a condition

2. The if Statement in C#

The if statement executes a block of code only when its condition is true.

Syntax

if (condition)
{
    // Code executes when the condition is true.
}

The condition must be a Boolean expression.

Example

int age = 20;

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}

Output:

You are an adult.

Because age >= 18 evaluates to true, the message is printed.

Example: Checking Exam Marks

int marks = 80;

if (marks >= 40)
{
    Console.WriteLine("Congratulations! You passed.");
}

Output:

Congratulations! You passed.

If marks were less than 40, the code inside the if block would not execute.

When Should You Use if?

Use an if statement when you want to execute an action only when a particular condition is satisfied.

Examples include:

  • Checking whether a user is logged in.

  • Verifying whether an account balance is sufficient.

  • Displaying a warning when inventory is low.

  • Checking whether a number is positive.

3. The if-else Statement in C#

The if-else statement provides two alternative execution paths.

If the condition is true, the if block executes. Otherwise, the else block executes.

Syntax

if (condition)
{
    // Executes when the condition is true.
}
else
{
    // Executes when the condition is false.
}

Example: Even or Odd Number

int number = 7;

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

Output:

Odd number

The modulus operator % returns the remainder after division. If a number divided by 2 has a remainder of zero, it is even; otherwise, it is odd.

Example: Pass or Fail

int marks = 35;

if (marks >= 40)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Fail");
}

Output:

Fail

The condition is false because 35 is less than 40, so the else block executes.

Example: Positive or Non-Positive Number

int number = 0;

if (number > 0)
{
    Console.WriteLine("Positive number");
}
else
{
    Console.WriteLine("Zero or negative number");
}

Output:

Zero or negative number

Notice that zero is neither positive nor negative. If you need to distinguish zero explicitly, use an else-if statement.

4. The else-if Ladder in C#

An else-if ladder allows you to evaluate multiple conditions in sequence.

C# checks the conditions from top to bottom. The first condition that evaluates to true has its block executed, and the remaining branches are skipped.

Syntax

if (condition1)
{
    // First block
}
else if (condition2)
{
    // Second block
}
else if (condition3)
{
    // Third block
}
else
{
    // Default block
}

Example: Grade Calculator

int marks = 85;

if (marks >= 90)
{
    Console.WriteLine("Grade A");
}
else if (marks >= 80)
{
    Console.WriteLine("Grade B");
}
else if (marks >= 70)
{
    Console.WriteLine("Grade C");
}
else if (marks >= 40)
{
    Console.WriteLine("Grade D");
}
else
{
    Console.WriteLine("Fail");
}

Output:

Grade B

The first condition, marks >= 90, is false. The second condition, marks >= 80, is true, so the program displays Grade B.

Why Does the Order Matter?

Suppose the conditions were written in this order:

int marks = 95;

if (marks >= 40)
{
    Console.WriteLine("Grade D");
}
else if (marks >= 80)
{
    Console.WriteLine("Grade B");
}

Output:

Grade D

The first condition is already true, so the second condition is never checked.

Best practice: Arrange overlapping conditions from the most specific or highest threshold to the least specific, as appropriate for the business rules.

5. Nested if Statements in C#

A nested if statement is an if statement placed inside another if or else block.

It is useful when a second decision should be made only after a first condition is satisfied.

Syntax

if (condition1)
{
    if (condition2)
    {
        // Executes when both conditions are true.
    }
}

Example: Login Validation

bool isRegistered = true;
bool passwordCorrect = true;

if (isRegistered)
{
    if (passwordCorrect)
    {
        Console.WriteLine("Login successful.");
    }
    else
    {
        Console.WriteLine("Incorrect password.");
    }
}
else
{
    Console.WriteLine("User is not registered.");
}

Output:

Login successful.

The program checks registration first and then verifies the password.

This is a simplified demonstration of conditional logic, not a complete authentication system. Real applications should use secure password verification and established authentication mechanisms.

Example: Checking Eligibility

int age = 22;
bool hasQualification = true;

if (age >= 18)
{
    if (hasQualification)
    {
        Console.WriteLine("Eligible to apply.");
    }
    else
    {
        Console.WriteLine("Required qualification is missing.");
    }
}
else
{
    Console.WriteLine("Minimum age requirement not met.");
}

Output:

Eligible to apply.

Nested conditions are useful, but deeply nested code can become difficult to maintain. Consider combining conditions with logical operators when that improves readability.

6. The switch Statement in C#

A switch statement selects a branch based on the value of an expression or a matching pattern.

It is particularly useful when a variable may match one of several distinct cases.

Syntax

switch (expression)
{
    case value1:
        // Code for value1
        break;

    case value2:
        // Code for value2
        break;

    default:
        // Code when no case matches
        break;
}

In a traditional switch statement, break commonly ends the selected section and prevents execution from continuing into another case. Other valid control-flow statements, such as return, may also be used.

Example: Day of the Week

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;

    case 2:
        Console.WriteLine("Tuesday");
        break;

    case 3:
        Console.WriteLine("Wednesday");
        break;

    case 4:
        Console.WriteLine("Thursday");
        break;

    case 5:
        Console.WriteLine("Friday");
        break;

    default:
        Console.WriteLine("Invalid day");
        break;
}

Output:

Wednesday

The value of day matches case 3, so the program displays Wednesday.

Example: Simple Calculator Menu

char operation = '+';
double a = 10;
double b = 5;

switch (operation)
{
    case '+':
        Console.WriteLine(a + b);
        break;

    case '-':
        Console.WriteLine(a - b);
        break;

    case '*':
        Console.WriteLine(a * b);
        break;

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

    default:
        Console.WriteLine("Invalid operation.");
        break;
}

Output:

15

This example selects an arithmetic operation based on the value stored in operation.

7. The default Case in a Switch Statement

The default case executes when no other case matches the expression.

It is optional, but it is useful when you need to handle unexpected or unsupported values.

Example

int menuOption = 10;

switch (menuOption)
{
    case 1:
        Console.WriteLine("View profile");
        break;

    case 2:
        Console.WriteLine("Edit profile");
        break;

    case 3:
        Console.WriteLine("Log out");
        break;

    default:
        Console.WriteLine("Invalid menu option");
        break;
}

Output:

Invalid menu option

Because 10 does not match any of the listed cases, the default branch executes.

8. The switch Expression in C#

A switch expression is a concise way to select and return a value based on a matching case.

Unlike a traditional switch statement, a switch expression produces a value that can be assigned to a variable or used in another expression.

Syntax

var result = expression switch
{
    pattern1 => value1,
    pattern2 => value2,
    _ => defaultValue
};

The underscore _ is a discard pattern that matches any value not handled by earlier arms.

Example: Grade Description

int marks = 85;

string grade = marks switch
{
    >= 90 => "Excellent",
    >= 80 => "Very Good",
    >= 70 => "Good",
    >= 40 => "Pass",
    _ => "Fail"
};

Console.WriteLine(grade);

Output:

Very Good

The switch expression checks its arms in order and selects the first matching pattern.

Advantages of Switch Expressions

  • They produce a value directly.

  • They can reduce repetitive assignment statements.

  • They make simple mappings concise.

  • They support pattern matching and relational patterns.

  • They work well with modern C# syntax.

9. What Is Pattern Matching in C#?

Pattern matching allows you to check whether a value satisfies a particular pattern.

Patterns can match constants, types, ranges, null values, and more complex data structures.

Pattern matching can make conditional logic more expressive and readable than writing numerous separate checks.

Common patterns include:

Pattern Purpose
Constant pattern Matches a specific constant value
Type pattern Checks whether a value has a specified type
Relational pattern Compares a value against a relational boundary
Logical pattern Combines patterns using and, or, or not
Property pattern Checks properties of an object
Null pattern Checks whether a value is null

Pattern matching is supported by both is expressions and switch statements or expressions.

10. Constant Pattern Matching

A constant pattern matches a value against a constant such as a number, character, string, Boolean, or null.

Example

int number = 10;

if (number is 10)
{
    Console.WriteLine("The number is ten.");
}

Output:

The number is ten.

The expression number is 10 checks whether the value is equal to the constant 10.

Example: String Matching

string role = "Admin";

if (role is "Admin")
{
    Console.WriteLine("Administrator access selected.");
}

Output:

Administrator access selected.

Constant patterns can make simple equality checks more expressive.

11. Type Pattern Matching

A type pattern checks whether a value is compatible with a specified type.

It is particularly useful when a variable is declared as object or another base type but may contain values of different runtime types.

Example

object value = "Hello, C#";

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

Output:

8

The condition checks whether value is a string. If the match succeeds, the variable text refers to the string value inside the if block.

Example: Handling Different Types

object value = 100;

if (value is int number)
{
    Console.WriteLine("Integer value: " + number);
}
else if (value is string text)
{
    Console.WriteLine("String value: " + text);
}
else
{
    Console.WriteLine("Unknown type");
}

Output:

Integer value: 100

Type patterns help avoid unsafe assumptions about the runtime type of a value.

12. Relational Pattern Matching

Relational patterns match values based on comparisons such as greater than, less than, or equal to a boundary.

C# supports relational patterns including:

  • <

  • >

  • <=

  • >=

They are especially useful in switch expressions that classify values into ranges.

Example: Temperature Classification

int temperature = 32;

string status = temperature switch
{
    < 0 => "Freezing",
    < 15 => "Cold",
    < 25 => "Moderate",
    <= 35 => "Warm",
    _ => "Hot"
};

Console.WriteLine(status);

Output:

Warm

The value 32 does not match the first three arms, but it satisfies <= 35.

Example: Age Classification

int age = 16;

string category = age switch
{
    < 0 => "Invalid age",
    < 13 => "Child",
    < 18 => "Teenager",
    < 60 => "Adult",
    _ => "Senior"
};

Console.WriteLine(category);

Output:

Teenager

Because the conditions are evaluated in order, age = 16 matches the < 18 arm after the earlier checks fail.

13. Logical Pattern Matching

Logical patterns let you combine or negate patterns using three keywords:

  • and

  • or

  • not

These are pattern-matching keywords and are distinct from the Boolean operators &&, ||, and !.

Example: Range Check

int number = 25;

if (number is >= 1 and <= 100)
{
    Console.WriteLine("Number is within the range.");
}

Output:

Number is within the range.

The condition matches when number is at least 1 and no greater than 100.

Example: Matching Multiple Values

string day = "Saturday";

if (day is "Saturday" or "Sunday")
{
    Console.WriteLine("It's the weekend.");
}
else
{
    Console.WriteLine("It's a weekday.");
}

Output:

It's the weekend.

Example: Negating a Pattern

string? username = null;

if (username is not null)
{
    Console.WriteLine("Username is available.");
}
else
{
    Console.WriteLine("Username is null.");
}

Output:

Username is null.

Logical patterns are helpful when multiple conditions can be expressed as a concise pattern.

14. Property Pattern Matching

Property patterns allow you to inspect one or more properties of an object.

They are useful when a decision depends on the state of an object rather than a single primitive value.

Example

class Student
{
    public string Name { get; set; } = "";
    public int Marks { get; set; }
}

class Program
{
    static void Main()
    {
        Student student = new Student
        {
            Name = "Rahul",
            Marks = 85
        };

        if (student is { Marks: >= 80 })
        {
            Console.WriteLine("High-performing student.");
        }
    }
}

Output:

High-performing student.

The property pattern { Marks: >= 80 } matches objects whose Marks property satisfies the condition.

Example: Matching Multiple Properties

class Product
{
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public bool InStock { get; set; }
}

class Program
{
    static void Main()
    {
        Product product = new Product
        {
            Name = "Laptop",
            Price = 50000m,
            InStock = true
        };

        if (product is { Price: < 60000m, InStock: true })
        {
            Console.WriteLine("Product is available within budget.");
        }
    }
}

Output:

Product is available within budget.

Property patterns can help keep business rules readable as an application grows.

15. The Conditional Operator (?:)

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

The operator evaluates the condition and returns one of the two values.

Use it for straightforward choices. If the logic becomes complex or requires multiple statements, prefer if-else or another suitable construct.

16. Difference Between If-Else and Switch

Both if-else and switch can control program flow, but they are suited to different kinds of decisions.

Feature If-Else Switch
Best suited for General Boolean conditions Multiple alternatives based on values or patterns
Range comparisons Very natural Supported through relational patterns
Complex logical conditions Often convenient Possible through patterns and guards
Readability Good for simple decisions Good for many distinct alternatives
Return a value directly Can use a conditional expression or assignment Switch expressions return a value
Default branch else default in a switch statement or _ in a switch expression

If-Else Example

int marks = 75;

if (marks >= 80)
{
    Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
    Console.WriteLine("Grade B");
}
else
{
    Console.WriteLine("Grade C");
}

Switch Example

int day = 2;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;

    case 2:
        Console.WriteLine("Tuesday");
        break;

    default:
        Console.WriteLine("Other day");
        break;
}

Use the construct that makes the business rule easiest to understand. A switch expression with relational patterns can also handle ranges concisely.

17. Practical Example: Student Grade Management System

Let's combine conditional statements to create a small grade-management program.

Requirements

  • Store a student's name.

  • Store the student's marks.

  • Validate whether marks are within the range from 0 to 100.

  • Determine the grade.

  • Display the result.

Complete Program

using System;

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

        if (marks < 0 || marks > 100)
        {
            Console.WriteLine("Invalid marks.");
            return;
        }

        string grade = marks switch
        {
            >= 90 => "A",
            >= 80 => "B",
            >= 70 => "C",
            >= 60 => "D",
            >= 40 => "E",
            _ => "F"
        };

        Console.WriteLine("Student Name: " + studentName);
        Console.WriteLine("Marks: " + marks);
        Console.WriteLine("Grade: " + grade);

        if (marks >= 40)
        {
            Console.WriteLine("Status: Pass");
        }
        else
        {
            Console.WriteLine("Status: Fail");
        }
    }
}

Output:

Student Name: Rahul
Marks: 85
Grade: B
Status: Pass

This program combines validation, logical operators, a switch expression, relational patterns, and an if-else statement.

18. Common Mistakes When Using Conditional Statements

Mistake 1: Using = Instead of ==

The = operator assigns a value. The == operator compares values for equality.

int number = 10;

if (number == 10)
{
    Console.WriteLine("Number is ten.");
}

Use the comparison operator when you want to test whether values are equal.

Mistake 2: Incorrect Condition Order

int marks = 90;

if (marks >= 40)
{
    Console.WriteLine("Pass");
}
else if (marks >= 80)
{
    Console.WriteLine("High grade");
}

The output is Pass, because the first condition is true. The second condition is never reached.

Place the more restrictive grade conditions first when implementing a grade ladder.

Mistake 3: Forgetting the Default Branch

When a switch statement does not include a default case, unexpected values may not produce any output.

Include a default branch when unsupported values need to be handled.

Mistake 4: Forgetting to End a Traditional Switch Case

In a traditional switch statement, a case cannot simply fall through into another non-empty case section. Use break, return, throw, or another appropriate control-flow statement.

Mistake 5: Confusing Boolean Operators and Logical Patterns

Boolean expressions commonly use &&, ||, and !.

Logical patterns use and, or, and not.

Although their purposes can be similar, their syntax and rules differ.

Mistake 6: Creating Deeply Nested Conditions

Too many nested if statements can make a program difficult to maintain. Consider combining conditions, extracting methods, or using pattern matching when doing so improves clarity.

Mistake 7: Forgetting to Validate Input Ranges

A value may be successfully converted to an integer but still be outside the allowed business range. Validate both the data type and the acceptable values.

19. Best Practices for Conditional Statements

Follow these practices when writing C# conditional logic:

  1. Keep conditions simple and readable.

  2. Use braces around conditional blocks, even when a block contains only one statement.

  3. Order overlapping else-if conditions carefully.

  4. Use switch when several alternatives depend on a common value.

  5. Use switch expressions when you need to select and return a value.

  6. Use pattern matching to make type checks and range checks more expressive.

  7. Include appropriate default handling for unexpected values.

  8. Avoid deeply nested conditions when simpler logic is possible.

  9. Validate user input before relying on it.

  10. Test boundary cases, including zero, negative values, minimum values, and maximum values.

20. Practice Exercise

Create a C# program for a simple online shopping discount system.

Requirements

  • Declare a variable for the customer's purchase amount.

  • Apply a discount based on the following rules:

    • Amount below 1000: No discount.

    • Amount from 1000 to below 5000: 5% discount.

    • Amount from 5000 to below 10000: 10% discount.

    • Amount of 10000 or more: 15% discount.

  • Calculate the discount amount.

  • Calculate the final amount.

  • Display the purchase amount, discount, and final amount.

Sample Solution

using System;

class Program
{
    static void Main()
    {
        decimal purchaseAmount = 7500m;

        if (purchaseAmount < 0)
        {
            Console.WriteLine("Invalid purchase amount.");
            return;
        }

        decimal discountRate = purchaseAmount switch
        {
            < 1000m => 0m,
            < 5000m => 0.05m,
            < 10000m => 0.10m,
            _ => 0.15m
        };

        decimal discount = purchaseAmount * discountRate;
        decimal finalAmount = purchaseAmount - discount;

        Console.WriteLine($"Purchase Amount: {purchaseAmount:F2}");
        Console.WriteLine($"Discount: {discount:F2}");
        Console.WriteLine($"Final Amount: {finalAmount:F2}");
    }
}

Output:

Purchase Amount: 7500.00
Discount: 750.00
Final Amount: 6750.00

This example demonstrates how relational patterns can be used in a switch expression to select a discount rate.

21. Frequently Asked Questions (FAQs)

1. What are conditional statements in C#?

Conditional statements allow a program to choose which code to execute based on whether a condition is true or false.

2. What is the difference between if and if-else?

An if statement executes code only when its condition is true. An if-else statement provides a second block that executes when the condition is false.

3. What is an else-if ladder?

An else-if ladder evaluates multiple conditions in sequence and executes the first matching branch.

4. What is a nested if statement?

A nested if statement is an if statement inside another conditional block. It is useful when a decision depends on an earlier condition.

5. What is the purpose of the switch statement?

The switch statement selects a branch based on a value or matching pattern. It is useful when several alternatives need to be handled clearly.

6. What is a switch expression in C#?

A switch expression evaluates patterns and produces a result. It can be assigned to a variable or used within another expression.

7. What is pattern matching in C#?

Pattern matching checks whether a value satisfies a pattern, such as a constant, type, range, or property condition.

8. What is the difference between && and and?

&& is a Boolean logical AND operator. and is used to combine patterns in pattern-matching expressions.

9. Can switch expressions check ranges?

Yes. Relational patterns such as <, >, <=, and >= allow switch expressions to classify values into ranges.

10. When should I use if-else instead of switch?

Use if-else when evaluating general conditions or complex Boolean logic. Use switch when multiple alternatives can be expressed clearly as value or pattern matches.

22. Quiz: Test Your Knowledge

Question 1: Which statement executes a block only when its condition is true?

A. switch
B. if
C. break
D. return

Question 2: What is the output of this code?

int number = 10;

if (number > 5)
{
    Console.WriteLine("A");
}
else
{
    Console.WriteLine("B");
}

A. A
B. B
C. Both A and B
D. No output

Question 3: Which branch executes when no case matches in a traditional switch statement?

A. break
B. else
C. default
D. continue

Question 4: What does a switch expression return?

A. It always returns a Boolean value.
B. It produces a value selected by a matching arm.
C. It always returns a string.
D. It cannot be assigned to a variable.

Question 5: Which is a valid relational pattern?

A. is >= 10
B. is = 10
C. is ==>
D. is => 10

Question 6: Which keywords combine patterns in C# pattern matching?

A. &&, ||, !
B. and, or, not
C. if, else, break
D. case, return, while

Quiz Answers

  1. B — if

  2. A — A

  3. C — default

  4. B — It produces a value selected by a matching arm.

  5. A — is >= 10

  6. B — and, or, not

Conclusion

Conditional statements allow C# programs to make decisions and respond to different situations. The if, if-else, and else-if constructs handle general conditions, while traditional switch statements and switch expressions make multiple alternatives easier to organize.

Pattern matching extends these capabilities by allowing you to match constants, types, ranges, and object properties.

As you build more complex applications, choosing the right conditional construct will help you write code that is easier to understand, test, and maintain.

←
Post 7 of 30
→