C# Else if Statement

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

C# Else if Statement Syntax

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

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

C# Else If Statement Example

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

This example read numbers from 1 to 4 and printed them in words. If the user-given number is not between 1 to 4, then print it 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");
        }
    }
}
C# Else If Example 1

ANALYSIS

Here i = 2 is given as the user input.

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

In the next iteration, it checks 2==2 and returns true.

Hence it prints: the input number is two.

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

Categories C#