Nesting if Statements
You can nesting if statements in C#. This is simply placing if statements inside if statements. You can make something as complex as the code that follows.
if (condition)
{
code to execute;
if (condition)
{
code to execute;
}
else if (condition)
{
if (condition)
{
code to execute;
}
}
}
else
{
if (condition)
{
code to execute;
}
}
Let’s try a program that uses nested if statements.
using System;
namespace NestingIfStatementsDemo
{
public class Program
{
public static void Main()
{
int age;
string gender;
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your gender (male/female): ");
gender = Console.ReadLine();
if (age > 12)
{
if (age < 20)
{
if (gender == "male")
{
Console.WriteLine("You are a teenage boy.");
}
else
{
Console.WriteLine("You are a teenage girl.");
}
}
else
{
Console.WriteLine("You are already an adult.");
}
}
else
{
Console.WriteLine("You are still too young.");
}
}
}
}
Example 1 – Nesting if Statements
Enter your age: 18 Enter your gender: male You are a teenage boy.
Enter your age: 12 Enter your gender: female You are still too young.
Let’s dissect the program. First, the program will ask you for your age (line 13). Line 16 asks for your gender. Then the program will hit the first if statement in line 18. It will test if you will past the first condition and that’s if your age is greater than 12. If you pass this condition, you will move inside the body of the if statement. If not, you jump to the corresponding else block (line 34) of that ifstatement. Let’s say you pass the first condition, and you are now inside the block of the first if statement. Inside it, you will meet a second nested if statement (line 20). It will determine if your age is less than 20. If you pass this, you will be taken into its code block, but if not, you will jump again to the it’s else pair in line 31. Let’s assume the value of your age is indeed less than 20, then you will be taken inside its body and there you will encounter yet another if statement (line 22). This will look at your gender and if it is “male”, then you will execute the code inside the body of the 3rd if statement, if not, it will execute the body of the else statement (line 26). The nesting ends there. If possible, avoid so much nesting of if statements. This makes your code very confusing to read. You can avoid using too many nested if statements using logical operators.