Conditional statements are essential in programming, enabling developers to perform different actions based on conditions. In C#, if
/else
statements are among the most basic yet powerful tools for decision-making in code. This article explains the syntax, uses, and best practices for if
/else
statements in C#, including practical examples and a simple application.
What is an if
/else
Statement?
An if
/else
statement is a conditional structure that executes code blocks based on specific conditions. If a condition is true
, the code within the if
block runs; otherwise, the code in the else
block (if provided) will execute.
Basic Syntax:
csharp if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
Step-by-Step Guide: Writing if
/else
Statements in C#
1. Basic Example: Checking Age Eligibility
Let’s start with a simple example. Suppose we want to check if a person is eligible to vote, assuming the legal voting age is 18.
csharp int age = 20; if (age >= 18) { Console.WriteLine("Eligible to vote."); } else { Console.WriteLine("Not eligible to vote."); }
Explanation: Here, we check if the age
variable is 18 or older. If it is, the program outputs "Eligible to vote." Otherwise, it outputs "Not eligible to vote."
2. Adding Complexity with else if
If you need to check multiple conditions, you can add else if
blocks to your code. Let’s look at an example that determines grades based on scores.
csharp int score = 75; 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"); }
Explanation: In this example, the program checks each condition in sequence. If a condition is true, it executes that block and skips the rest. This logic is often used in grading systems or any scenario with tiered decision-making.
3. Nested if
Statements
You can also nest if
statements within each other. For instance, let’s check both age and citizenship to determine voting eligibility.
csharp int age = 20; bool isCitizen = true; if (age >= 18) { if (isCitizen) { Console.WriteLine("Eligible to vote."); } else { Console.WriteLine("Not a citizen, not eligible to vote."); } } else { Console.WriteLine("Not eligible to vote due to age."); }
Explanation: The program first checks if the person’s age is 18 or older. If so, it checks the isCitizen
condition. Nested if
statements can be helpful but should be used sparingly to avoid code that is hard to read.
Real-Life Example: ATM Withdrawal Simulation
Let’s build a simple application that simulates ATM withdrawals. The program will check if the account balance is sufficient before allowing a withdrawal.
csharp decimal balance = 500m; decimal withdrawalAmount = 200m; if (withdrawalAmount <= balance) { balance -= withdrawalAmount; Console.WriteLine($"Withdrawal successful! New balance: {balance}"); } else { Console.WriteLine("Insufficient funds."); }
Explanation: Here, we check if the withdrawalAmount
is less than or equal to the balance
. If so, the withdrawal is successful, and the new balance is displayed. Otherwise, it notifies the user of insufficient funds.
Best Practices for if
/else
Statements
- Avoid Overusing Nested
if
Statements: Deeply nestedif
statements can make your code hard to read and maintain. Consider alternative structures, like using logical operators. - Use
else if
for Multiple Conditions: When you need to check multiple conditions,else if
helps keep the code organized. Use it when only one condition needs to be true. - Combine Conditions with Logical Operators: Combine multiple conditions in a single
if
statement when possible to reduce nesting.
csharp if (age >= 18 && isCitizen) { Console.WriteLine("Eligible to vote."); }
- Minimize Redundant Checks: If you check the same condition multiple times, consider restructuring the code to avoid redundancy.
- Use Ternary Operators for Simple Conditions: For concise conditional assignments, consider using the ternary operator.
csharp string result = (score >= 50) ? "Passed" : "Failed";
- Prioritize Readability: Write
if
/else
conditions in a way that’s easy to read and understand. Comment complex conditions to help future developers. - Optimize for Performance: If some conditions are more likely to be true, check those first to minimize unnecessary checks.
Features of if
/else
Statements
- Boolean Conditions:
if
/else
statements rely on Boolean expressions to determine the flow of execution. - Control Flow:
if
/else
statements offer essential control over code execution based on varying conditions. - Conditional Operators: Logical (
&&
,||
) and comparison (==
,!=
,>
,<
) operators enhance the power ofif
/else
. - Readable Structure: C#'s syntax makes
if
/else
statements easy to read and understand.
Simple Application: Login Authentication System
Now, let’s create a basic login authentication system using if
/else
statements.
csharp string username = "admin"; string password = "password123"; Console.Write("Enter username: "); string inputUsername = Console.ReadLine(); Console.Write("Enter password: "); string inputPassword = Console.ReadLine(); if (inputUsername == username && inputPassword == password) { Console.WriteLine("Login successful!"); } else if (inputUsername != username) { Console.WriteLine("Username not found."); } else if (inputPassword != password) { Console.WriteLine("Incorrect password."); } else { Console.WriteLine("Login failed."); }
Explanation: This code checks both the username and password. If both match, it grants access. Otherwise, it specifies if the issue is the username, password, or both. This example demonstrates how conditional statements create different responses based on varying inputs.