C# Else if Statement

By using the C# Else if statements, we can increase the speed of execution over simple if statements. That means when we use C# Else if control flow statements, the compiler will check all the comparisons in the sequence only until the given condition is satisfied. Once the condition is satisfied, rather than going for the next comparison, it will exit there itself.

C# Else if Syntax

The Else if control statements will overcome the performance issues with the simple if statements. And the syntax behind this C# else if statement is as shown below 

if <condition>
{
  Statements //These statements are executed if condition is true
}
else if <condition>
{
  Statements //These statements are executed when this else if condition is true
}
else if <condition>
{
  Statements //These statements are executed when this else if condition is true
}
else
  <Default statements> //These statements are executed in case when neither of the above conditions is true. 

C# Else If Example

Let us write the simple example using else if statement. It is the same example that you saw in the if statement.

This C# example read numbers from 1 to 4 and print in words. If the user given number is not in between 1 to 4, then print as an invalid number.

using System;
class Program
{
    static void Main()
    {
        int i = int.Parse(Console.ReadLine());


        if (i == 1)
        {
            Console.WriteLine("input number is one");
        }
        else if (i == 2)
        {
            Console.WriteLine("input number is two");
        }
        else if (i == 3)
        {
            Console.WriteLine("input number is three");
        }
        else if (i == 4)
        {
            Console.WriteLine("input number is four");
        }
        else
        {
            Console.WriteLine("input number is invalid");
        }
    }
}

OUTPUT

C# Else If Example 1

ANALYSIS

Here i = 2 is given as input.

First, it checks for 2==1, which is false.

2==2 returns true

Hence it prints: input number is two

And it quit from the loop without executing the next statements.