The else if statement in C# is a conditional statement that allows you to check multiple conditions in sequence. It follows an initial if block and is used when you need to evaluate additional conditions after the first condition fails. Each else if block provides an alternative condition to test.
Syntax:
if (condition1)
{
// Executes if condition1 is true
}
else if (condition2)
{
// Executes if condition2 is true and condition1 is false
}
else
{
// Executes if none of the above conditions are true
}
Explanation:
- if: Evaluates the first condition.
- else if: Provides additional conditions to check if the previous if or else if conditions were false.
- else: A fallback option if none of the previous conditions are true.
Example:
using System;
public class MyData
{
public static void Main(string[] args)
{
int number = 25;
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.");
}
}
}
Output:
If we pass number= -25 in the above code then Output will be
If we pass number= 0 in the above code then Output will be
C# else if Condition – Interview Questions
Q 1: What is else if used for?
Q 2: Can multiple else if blocks be used?
Q 3: Is else if mandatory?
Q 4: Can else if exist without if?
Q 5: When is else executed?
C# else if Condition – Objective Questions (MCQs)
Q1. What is the purpose of else if in C#?
Q2. What will be the output of the following code?
int a = 7;
if(a > 10)
Console.WriteLine("A");
else if(a > 5)
Console.WriteLine("B");
else
Console.WriteLine("C");
Q3. Can multiple else if blocks be used after a single if block?
Q4. Which keyword is used to terminate checking further conditions if one condition is true?
Q5. Is the else block mandatory in an if-else if-else chain?