C# If Else Statements
Introduction
Decision making is an essential part of programming. In real life, we make decisions based on certain conditions, and computer programs work similarly. C# provides several decision-making statements that execute different blocks of code based on specified conditions.
The if-else
statement is one of the fundamental control flow structures in C#. It allows your program to make decisions and execute different code paths depending on whether a specified condition evaluates to true
or false
.
Basic If Statement
The simplest form of conditional execution is the if
statement. It executes a block of code only when a specified condition is true.
Syntax
if (condition)
{
// Code to execute if the condition is true
}
Example
int temperature = 28;
if (temperature > 25)
{
Console.WriteLine("It's a hot day!");
}
// Output: It's a hot day!
In this example, the message is displayed because the temperature (28) is greater than 25.
If-Else Statement
The if-else
statement extends the if
statement by providing an alternative block of code to execute when the condition is false.
Syntax
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example
int hour = 20;
if (hour < 18)
{
Console.WriteLine("Good day!");
}
else
{
Console.WriteLine("Good evening!");
}
// Output: Good evening!
In this example, since the hour (20) is not less than 18, the program executes the code in the else
block.
Multiple Conditions with Else If
When you need to check multiple conditions, you can use the else if
construct, which allows you to specify additional conditions to test if the previous condition was false.
Syntax
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition1 is false and condition2 is true
}
else if (condition3)
{
// Code to execute if condition1 and condition2 are false and condition3 is true
}
else
{
// Code to execute if all conditions are false
}
Example
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: B
In this example, the program checks the score against different ranges and assigns a grade accordingly. Since the score is 85, it falls in the B range.
Nested If Statements
You can also place an if
statement inside another if
statement, creating what's known as a nested if
statement.
Example
bool isWeekend = true;
bool isRaining = true;
if (isWeekend)
{
if (isRaining)
{
Console.WriteLine("Stay home and watch a movie");
}
else
{
Console.WriteLine("Go out and enjoy the weekend");
}
}
else
{
Console.WriteLine("It's a workday");
}
// Output: Stay home and watch a movie
In this example, the program first checks if it's a weekend. Since it is, it then checks if it's raining. As it is raining, it suggests staying home.
Logical Operators in Conditions
C# provides logical operators (&&
for AND, ||
for OR, !
for NOT) that you can use to combine multiple conditions in a single if
statement.
Example
int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense)
{
Console.WriteLine("You can drive a car");
}
else if (age >= 18 && !hasLicense)
{
Console.WriteLine("You need to get a license first");
}
else
{
Console.WriteLine("You are too young to drive");
}
// Output: You can drive a car
In this example, both conditions (age >= 18 AND hasLicense is true) must be true for the first code block to execute.
The Conditional (Ternary) Operator
C# provides a shorthand for simple if-else
statements known as the conditional operator or the ternary operator.
Syntax
condition ? expression_if_true : expression_if_false
Example
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine($"Status: {status}");
// Output: Status: Adult
This example checks if the age is 18 or older. If it is, the status is set to "Adult"; otherwise, it's set to "Minor".
Real-World Examples
Example 1: User Authentication
string storedUsername = "user123";
string storedPassword = "pass123";
string inputUsername = "user123";
string inputPassword = "pass123";
if (inputUsername == storedUsername)
{
if (inputPassword == storedPassword)
{
Console.WriteLine("Login successful!");
}
else
{
Console.WriteLine("Incorrect password!");
}
}
else
{
Console.WriteLine("Username not found!");
}
// Output: Login successful!
Example 2: Weather App Suggestion
int temperature = 28;
bool isRaining = false;
if (temperature > 30)
{
Console.WriteLine("It's very hot outside!");
if (isRaining)
{
Console.WriteLine("Unusual weather: Hot and rainy!");
}
}
else if (temperature > 20)
{
if (isRaining)
{
Console.WriteLine("Take an umbrella, it's warm but rainy.");
}
else
{
Console.WriteLine("Nice weather for a walk!");
}
}
else if (temperature > 10)
{
Console.WriteLine("It's a bit cool outside.");
}
else
{
Console.WriteLine("It's cold, wear a jacket!");
}
// Output: Nice weather for a walk!
Example 3: Discount Calculator
double totalPurchase = 120.50;
bool isMember = true;
string couponCode = "SAVE10";
double discount = 0;
if (totalPurchase >= 100)
{
discount += 5; // 5% discount for purchases over $100
if (isMember)
{
discount += 10; // Additional 10% discount for members
}
if (couponCode == "SAVE10")
{
discount += 10; // Additional 10% for valid coupon code
}
}
else if (totalPurchase >= 50)
{
discount += 2; // 2% discount for purchases over $50
if (isMember)
{
discount += 5; // Additional 5% discount for members
}
}
double finalPrice = totalPurchase * (1 - discount / 100);
Console.WriteLine($"Total purchase: ${totalPurchase}");
Console.WriteLine($"Discount applied: {discount}%");
Console.WriteLine($"Final price: ${finalPrice:F2}");
/* Output:
Total purchase: $120.5
Discount applied: 25%
Final price: $90.38
*/
Best Practices
-
Keep conditions simple: Try to keep your conditions as simple and readable as possible.
-
Use braces: Always use braces
{}
even for single-line statements to improve readability and prevent errors. -
Be careful with equality checks: Use
==
for equality comparison, not=
which is for assignment. -
Avoid deep nesting: If you find yourself nesting many levels deep, consider refactoring your code.
-
Watch for null values: When working with objects, check for nulls to avoid NullReferenceExceptions.
string name = null;
// Bad practice - might cause a NullReferenceException
if (name.Length > 0) { }
// Good practice - check for null first
if (name != null && name.Length > 0) { }
// Even better in modern C# - use the null conditional operator
if (name?.Length > 0) { }
Summary
Conditional statements are fundamental to programming as they enable your code to make decisions. In C#, the primary conditional construct is the if-else
statement, which can be extended with else if
for multiple conditions. For simple conditionals, the ternary operator provides a concise alternative.
Remember that conditionals evaluate expressions to Boolean values (true
or false
), and you can combine multiple conditions using logical operators (&&
, ||
, !
).
By mastering conditionals, you gain the ability to create more dynamic and responsive applications that can adapt to various situations and user inputs.
Exercises
-
Write a program that takes a user's age as input and outputs different messages based on age ranges (child, teenager, adult, senior).
-
Create a simple calculator that takes two numbers and an operation (+, -, *, /) as input and performs the appropriate calculation using if-else statements.
-
Write a program that checks if a year is a leap year. (Hint: A leap year is divisible by 4, but not by 100 unless it's also divisible by 400).
-
Create a program that determines the shipping cost based on the purchase amount and destination (local, domestic, international).
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)