C# else Statement
The else statement in C# is used in conjunction with an if statement to execute a block of code when the if condition evaluates to false. It provides an alternative path of execution.
Key Topics
1. Syntax of else Statement
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
2. Basic else Statement Example
Example: Checking Even or Odd
int number = 7;
if (number % 2 == 0)
{
Console.WriteLine("The number is even.");
}
else
{
Console.WriteLine("The number is odd.");
}
Output:
The number is odd.
Code Explanation: The condition number % 2 == 0 checks if the number is divisible by 2. Since 7 is not divisible by 2, the condition is false, and the code inside the else block is executed.
3. Combining if and else
The else block is optional and can be added to an if statement to handle cases when the condition is not met.
Example: Age Verification
int age = 16;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not eligible to vote.");
}
Output:
You are not eligible to vote.
4. Best Practices for else Statements
- Use the
elsestatement to handle all other cases when theifcondition is false. - Keep the
if-elseblocks aligned and properly indented for readability. - Avoid unnecessary
elsestatements if the logic can be simplified.
Key Takeaways
- The
elsestatement provides an alternative path when theifcondition is false. - Combining
ifandelseallows for handling binary decisions. - Proper structure and readability are important for maintaining clean code.