C# else if Condition

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:

The number is positive.

If we pass number= -25 in the above code then Output will be

The number is negative.

If we pass number= 0 in the above code then Output will be

The number is zero.

C# else if Condition – Interview Questions

Q 1: What is else if used for?
Ans: To check multiple conditions.
Q 2: Can multiple else if blocks be used?
Ans: Yes.
Q 3: Is else if mandatory?
Ans: No.
Q 4: Can else if exist without if?
Ans: No.
Q 5: When is else executed?
Ans: When all conditions are false.

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?






Related C# else if Condition Topics