Lesson 2.2.2 The IF…ELSE statement

This is a nicety on top of the usual IF statements. Take the earlier example.

“If I’m not home when you call round, get the key from under the flower pot.”

It doesn’t actually give the listener any options if the speaker is in. What might be said instead is:

“If I’m not home when you call round, get the key from under the flower pot, otherwise I’ll let you in.”

On reflection it’s an obvious statement but you wouldn’t think anyone strange for saying it. C# allows you to do the same thing with your code. Take the example below. It is an expansion on the program that bid you a good afternoon if it was the PM. It will now bid a good morning if the opposite is true.

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

namespace GoodAfternoon2
{
    class Program
    {
        static void Main(string[] args)
        {
            if (DateTime.Now.Hour >= 12)
            {
                System.Console.WriteLine("Good afternoon World");
            }
            else
            {
                System.Console.WriteLine("Good morning World");
            }
            System.Console.ReadKey(true);

        }
    }
}

The flow of the code will execute what’s between the ELSE brackets if the IF condition is false.


Supporting files

File Description Open with
Good Afternoon project 2 Contains the altered "Good afternoon" console project Visual C# 2008