C# Nested If
Nested If
Sometimes you only want to check a condition when another condition is already true.
Think about how you log in to a website. First, the website checks your username. It only checks your password if the username is correct.
In C#, you can do this by placing an if statement inside another if statement. This is called a nested if:
Syntax
if (condition1)
{
// code to run if condition1 is true
if (condition2)
{
// code to run if condition1 and condition2 are both true
}
}
The inner if is only checked when the outer condition is true.
A Simple Example
In this example, we first check if x is greater than 10. If it is, we also check if y is greater than 20:
Example
int x = 15;
int y = 25;
if (x > 10)
{
Console.WriteLine("x is greater than 10");
if (y > 20)
{
Console.WriteLine("y is also greater than 20");
}
}
Example explained
x is 15, so x > 10 is true. The program prints the first message, and then it checks the inner if.
y is 25, so y > 20 is also true, and the program prints the second message.
If x was 5, the outer condition would be false. Then C# skips the whole block, and it never checks y.
Nested If with else
You can add an else to both the outer and the inner if. Each else runs when its own condition is false.
This example checks the username first, and then the password. The == operator also works with text (strings):
Example
string username = "Liam";
string password = "abc123";
if (username == "Liam")
{
if (password == "abc123")
{
Console.WriteLine("Welcome, Liam!");
}
else
{
Console.WriteLine("Wrong password.");
}
}
else
{
Console.WriteLine("Unknown user.");
}
Both the username and the password are correct, so the program prints "Welcome, Liam!".
Try to change the values in the editor:
- With a wrong
password, the innerelseruns and prints "Wrong password." - With a wrong
username, the outerelseruns and prints "Unknown user."
When to Use a Nested If
A nested if is useful when the second check only makes sense after the first one, and each step needs its own message, like "Unknown user." and "Wrong password." above.
You can place an if inside an if inside another if, but each new level makes the code harder to read. Try to keep it to two levels.