C sharp - Understanding else if in C#
The else if
statement in C# allows you to check multiple conditions one after another. It works as an extension of an if
statement, and it's useful when you have more than two possible outcomes.
Syntax
if (condition1)
{
// Executes if condition1 is true
}
else if (condition2)
{
// Executes if condition2 is true
}
else if (condition3)
{
// Executes if condition3 is true
}
else
{
// Executes if none of the above conditions are true
}
How it Works
-
C# checks conditions in order from top to bottom.
-
The first condition that evaluates to
true
will have its block executed. -
Once a match is found, the rest are ignored.
-
If none are
true
, theelse
block runs (if provided).
Example: Grading System
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");
}
Output:
Grade: B
Key Points to Remember
-
else if
is optional, and you can have multipleelse if
blocks. -
else
is also optional but is useful for a default action. -
Make sure conditions are mutually exclusive or in logical order to avoid unreachable code.