If-else statements are fundamental control structures in C# that allow programmers to execute different code blocks based on specific conditions. They enable decision-making in programs, enhancing their flexibility and functionality.
The basic syntax of an if-else statement in C# is as follows:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
When an if-else statement is encountered, the program evaluates the condition within the parentheses. If the condition is true, the code block immediately following the if
statement is executed. If the condition is false, the code block following the else
statement is executed instead.
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not eligible to vote yet.");
}
In this example, the program checks if the age
variable is greater than or equal to 18. If true, it prints that the person is eligible to vote; otherwise, it prints that they are not eligible.
For more complex decision-making, you can use else if
statements to check multiple conditions:
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
{
Console.WriteLine("Grade: F");
}
This example demonstrates how to use multiple conditions to assign grades based on a score. The program checks each condition in order and executes the first matching block.
You can also nest if-else statements within each other for more complex logic:
bool isWeekend = true;
bool isRaining = false;
if (isWeekend)
{
if (isRaining)
{
Console.WriteLine("Stay home and watch a movie.");
}
else
{
Console.WriteLine("Go out and enjoy the weather!");
}
}
else
{
Console.WriteLine("It's a workday.");
}
This example shows how to use nested if-else statements to make decisions based on multiple factors.
else if
for multiple related conditions.If-else statements are crucial for implementing conditional logic in C# programs. They allow you to create dynamic and responsive applications that can make decisions based on various conditions. As you progress in your C# journey, you'll find yourself using these statements frequently in combination with other control structures like loops and switch statements.