If, Else If, and Else Statements
Conditional statements allow your program to make decisions based on conditions. This is how you control the flow of your program.
The if Statement
The if statement executes code only when a condition is true:
csharp1int age = 20;23if (age >= 18)4{5 Console.WriteLine("You are an adult.");6}
Syntax
csharp1if (condition)2{3 // Code to execute when condition is true4}
The condition must be a boolean expression (evaluates to true or false).
The else Statement
The else statement provides an alternative when the condition is false:
csharp1int age = 16;23if (age >= 18)4{5 Console.WriteLine("You are an adult.");6}7else8{9 Console.WriteLine("You are a minor.");10}
Output
You are a minor.
The else if Statement
Use else if to check multiple conditions:
csharp1int score = 85;23if (score >= 90)4{5 Console.WriteLine("Grade: A");6}7else if (score >= 80)8{9 Console.WriteLine("Grade: B");10}11else if (score >= 70)12{13 Console.WriteLine("Grade: C");14}15else if (score >= 60)16{17 Console.WriteLine("Grade: D");18}19else20{21 Console.WriteLine("Grade: F");22}
Output
Grade: B
How It Works
- Conditions are checked from top to bottom
- The first true condition's code block executes
- Remaining conditions are skipped
elseis optional and catches everything else
Nested if Statements
You can put if statements inside other if statements:
csharp1bool isLoggedIn = true;2bool isAdmin = true;34if (isLoggedIn)5{6 Console.WriteLine("Welcome!");78 if (isAdmin)9 {10 Console.WriteLine("You have admin access.");11 }12 else13 {14 Console.WriteLine("You have standard access.");15 }16}17else18{19 Console.WriteLine("Please log in.");20}
Avoiding Deep Nesting
Deep nesting can be hard to read. Consider restructuring:
csharp1// Hard to read2if (condition1)3{4 if (condition2)5 {6 if (condition3)7 {8 // Do something9 }10 }11}1213// Better: combine conditions14if (condition1 && condition2 && condition3)15{16 // Do something17}1819// Or: use early returns20if (!condition1) return;21if (!condition2) return;22if (!condition3) return;23// Do something
Braces and Single Statements
For single statements, braces are optional (but recommended):
csharp1// Without braces (works but not recommended)2if (age >= 18)3 Console.WriteLine("Adult");4else5 Console.WriteLine("Minor");67// With braces (recommended)8if (age >= 18)9{10 Console.WriteLine("Adult");11}12else13{14 Console.WriteLine("Minor");15}
Always use braces to avoid bugs when adding more code later.
Common Patterns
Validation
csharp1Console.Write("Enter your age: ");2string input = Console.ReadLine() ?? "";34if (int.TryParse(input, out int age))5{6 if (age < 0 || age > 150)7 {8 Console.WriteLine("Please enter a valid age.");9 }10 else11 {12 Console.WriteLine($"You are {age} years old.");13 }14}15else16{17 Console.WriteLine("That's not a number.");18}
Range Checking
csharp1int temperature = 72;23if (temperature < 32)4{5 Console.WriteLine("Freezing!");6}7else if (temperature < 60)8{9 Console.WriteLine("Cold");10}11else if (temperature < 80)12{13 Console.WriteLine("Comfortable");14}15else16{17 Console.WriteLine("Hot!");18}
Null Checking
csharp1string? name = GetUserName(); // Might return null23if (name == null)4{5 Console.WriteLine("Name not provided");6}7else if (name.Length == 0)8{9 Console.WriteLine("Name is empty");10}11else12{13 Console.WriteLine($"Hello, {name}!");14}1516// Or use string.IsNullOrEmpty17if (string.IsNullOrEmpty(name))18{19 Console.WriteLine("Name not provided or empty");20}
Boolean Variables in Conditions
You don't need == true for boolean variables:
csharp1bool isActive = true;23// Unnecessary4if (isActive == true)5{6 Console.WriteLine("Active");7}89// Clean10if (isActive)11{12 Console.WriteLine("Active");13}1415// Checking for false16if (!isActive)17{18 Console.WriteLine("Inactive");19}
Practical Example
csharp1Console.WriteLine("=== Movie Ticket Price Calculator ===");2Console.Write("Enter your age: ");34if (!int.TryParse(Console.ReadLine(), out int age))5{6 Console.WriteLine("Invalid age!");7 return;8}910Console.Write("Is it a matinee showing? (yes/no): ");11string matineeInput = Console.ReadLine()?.ToLower() ?? "";12bool isMatinee = matineeInput == "yes" || matineeInput == "y";1314decimal price;1516if (age < 3)17{18 price = 0;19 Console.WriteLine("Free admission for children under 3!");20}21else if (age < 12)22{23 price = isMatinee ? 6.00m : 8.00m;24 Console.WriteLine("Child ticket");25}26else if (age >= 65)27{28 price = isMatinee ? 7.00m : 9.00m;29 Console.WriteLine("Senior discount applied");30}31else32{33 price = isMatinee ? 9.00m : 12.00m;34 Console.WriteLine("Adult ticket");35}3637Console.WriteLine($"Ticket price: {price:C}");
Summary
In this lesson, you learned:
ifexecutes code when a condition is trueelseprovides an alternative pathelse ifchecks multiple conditions in sequence- Conditions are checked top to bottom; first match wins
- Avoid deep nesting for readability
- Always use braces for clarity
Next, we'll learn about the ternary operator for simple conditional expressions.