C Sharp

Multiple else Clauses

The if statement's else clause enables you to specify an alternative course of action should the if statement resolve to false. In the number-guessing example, the application performed a simple compare between the number the user guessed and the randomly generated number. In that case, only two possibilities existed: the user was either correct or incorrect. You can also combine if and else to handle situations in which you want to test more than two conditions. In the example below, I ask the user which language he or she is currently using (excluding C#). I've included the ability to select from three languages, so the if statement must be able to deal with four possible answers: the three languages and the case in which the user selects an unknown language. Here's one way of programming this with an if/else statement: -

using System;
class IfTest2App
{
    const string CPlusPlus = "C++";
    const string VisualBasic = "Visual Basic";
    const string Java = "Java";
    public static void Main()
    {
        Console.Write("What is your current language of choice " +
                       "(excluding C#)?");
        string inputString = Console.ReadLine();
        if (0 == String.Compare(inputString, CPlusPlus, true))
        {
            Console.WriteLine("\nYou'll have no problem picking " +
                                 "up C# !");
        }
        else if (0 == String.Compare(inputString, VisualBasic, true))
        {
            Console.WriteLine("\nYou'll find lots of cool VB features " +
                                 "in C# !");
        }
        else if (0 == String.Compare(inputString, Java, true))
        {
            Console.WriteLine("\nYou'll have an easier time " +
                                 "picking up C# <G> !!");
        }
        else
        {
            Console.WriteLine("\nSorry - doesn't compute.");
        }
    }
}

Notice the use of the == operator to compare 0 to the returned value of String.Compare. This is because String.Compare will return -1 if the first string is less than the second string, 1 if the first string is greater than the second, and 0 if the two are identical. However, this illustrates some interesting details, described in the following section, about how C# enforces use of the if statement.

by BrainBellupdated
Advertisement: