C sharp - Nested if in C#: Explained

 

What is a Nested if?

A nested if is when one if statement is placed inside another if statement. It allows you to check multiple related conditions in a structured way.

Syntax:

if (condition1)
{
    if (condition2)
    {
        // Code to execute if both condition1 and condition2 are true
    }
}

Example 1: Simple Nested if

int age = 20;
bool hasID = true;

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

Output:

Access granted.

 Explanation:

  • First, it checks if age is 18 or older.

  • Then it checks if the person has an ID.

  • Only if both are true, the message is printed.

Example 2: With else Blocks

int age = 17;
bool hasID = true;

if (age >= 18)
{
    if (hasID)
    {
        Console.WriteLine("Access granted.");
    }
    else
    {
        Console.WriteLine("ID required.");
    }
}
else
{
    Console.WriteLine("You must be at least 18.");
}

 Output:

You must be at least 18.