Lesson 2.2.3 The IF… ELSEIF… ELSE statement

C# goes even further in its endeavours to give you flexible conditional code. This construct allows you to manage multiple possibilities.

The block of sample code below demonstrates.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodAfternoon3
{
    class Program
    {
        static void Main(string[] args)
        {
            if (DateTime.Now.Hour < 12)
            {
                System.Console.WriteLine("Good morning World");
            }
            else if (DateTime.Now.Hour < 18)
            {
                System.Console.WriteLine("Good afternoon World");
            }
            else if (DateTime.Now.Hour < 22)
            {
                System.Console.WriteLine("Good evening World");
            }
            else
            {
                System.Console.WriteLine("Good night World");
            }
            System.Console.ReadKey(true);

        }
    }
}

Hopefully, it shouldn’t be too hard to see what’s going on. The point of this coding construct is to ensure that only one of these blocks gets executed come what may. You can be sure that the program would only display one of these blocks of text. To illustrate this feature, I am going to introduce a bug in to the code.

 
  if (DateTime.Now.Hour < 12)
  {
      System.Console.WriteLine("Good morning World");
  }
  else if (DateTime.Now.Hour < 18)
  {
      System.Console.WriteLine("Good afternoon World");
  }
  else if (DateTime.Now.Hour < 18)
  {
      System.Console.WriteLine("Good evening World");
  }
  else
  {
      System.Console.WriteLine("Good night World");
  }
  System.Console.ReadKey(true);
 

Note that the condition to show “Good afternoon World” and to show “Good evening world” are now exactly the same. Which text would show? Simple, the code execution will go through all of the conditions and bail out the moment one of them is true. Therefore it would show “Good afternoon world”. A small point to make but in code the devil is in the detail.

Another important point to note is that you do not need the ELSE block at the end. Remove it from the example and you will simply find the program doesn’t write anything if it is 10pm or later.


Supporting files

File Description Open with
Good Afternoon project 3 Contains the altered (again) "Good afternoon" console project Visual C# 2008