In programming, making decisions is a fundamental task. C# provides several constructs to help you make these decisions, and one of the most common is the if-else statement. This tutorial will guide you through understanding how to use if-else statements in C# to control the flow of your programs.
The if-else statement allows your program to execute different blocks of code based on whether a condition evaluates to true or false. The basic syntax is as follows:
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
Here's how it works:
1. **Condition**: This is an expression that evaluates to either `true` or `false`.
2. **If Block**: The code inside this block will run only if the condition is `true`.
3. **Else Block**: The code inside this block will run only if the condition is `false`.
You can also use multiple conditions with `else if`:
```csharp
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
// Code to execute if none of the above conditions are true
}
## Examples
Let's look at some practical examples to understand how `if-else` statements work in C#.
### Example 1: Basic If-Else Statement
Suppose you want to check if a number is positive or negative:
```csharp
int number = -5;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is negative.");
}
<OutputBlock>
{`The number is negative.`}
</OutputBlock>
### Example 2: Using Else If
Let's extend the previous example to check for zero as well:
```csharp
int number = 0;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
The number is zero.
You can also nest if-else statements inside each other to handle more complex conditions:
int age = 20;
bool hasLicense = true;
if (age >= 18)
{
if (hasLicense)
{
Console.WriteLine("You are eligible to drive.");
}
else
{
Console.WriteLine("You are not eligible to drive because you don't have a license.");
}
}
else
{
Console.WriteLine("You are not eligible to drive because you are under 18.");
}
You are eligible to drive.
For simple conditions, you can use the ternary operator as a shorthand for if-else:
int number = 10;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(result);
Even
In the next section, we will explore another control flow construct called Switch Case Statements. This will help you handle multiple conditions in a more organized way.
Stay tuned for more tutorials and happy coding!