Home

Conditional Switches

 

The Ternary Operator (?:)

The conditional operator behaves like a simple if…else statement. Its syntax is:

Condition ? Statement1 : Statement2;

The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:

using System;

class NewProject
{
	static void Main()
	{
		int Number1, Number2, Maximum;
		string Num1, Num2;
	
		Console.Write("Enter first numbers: ");
		Num1 = Console.ReadLine();
		Console.Write("Enter second numbers: ");
		Num2 = Console.ReadLine();
		
		Number1 = int.Parse(Num1);
		Number2 = int.Parse(Num2);
	
		Maximum = (Number1 < Number2) ? Number2 : Number1;
	
		Console.Write("\nThe maximum of ");
		Console.Write(Number1);
		Console.Write(" and ");
		Console.Write(Number2);
		Console.Write(" is ");
		Console.WriteLine(Maximum);
	
		Console.WriteLine();
	}
}

Here is an example of running the program;

Enter first numbers: 244
Enter second numbers: 68

The maximum of 244 and 68 is 244

Practical LearningPractical Learning: Introducing Boolean Variables

  1. Start Microsoft Visual C#
  2. Create a new Console Application named FlowerShop2
  3. To create a new class, on the main menu, click Project -> Add Class...
  4. Set the Name of the class to Flower and click Add
  5. Complete the Flower.cs file as follows:
     
    using System;
    
    namespace FlowerShop2
    {
        public enum FlowerType
        {
            Roses = 1,
            Lilies,
            Daisies,
            Carnations,
            LivePlant,
            Mixed
        }
    
        public enum FlowerColor
        {
            Red = 1,
            White,
            Yellow,
            Pink,
            Orange,
            Blue,
            Lavender,
            Mixed
        }
    
        public enum FlowerArrangement
        {
            Bouquet = 1,
            Vase,
            Basket,
            Any
        }
    
        class Flower
        {
            public FlowerType Type;
            public FlowerColor Color;
            public FlowerArrangement Arrangement;
            public decimal UnitPrice;
    
            public Flower()
            {
                Type = FlowerType.Mixed;
                Color = FlowerColor.Mixed;
                Arrangement = FlowerArrangement.Vase;
                UnitPrice = 0.00M;
            }
            public Flower(FlowerType type)
            {
                Type = type;
                Color = FlowerColor.Mixed;
                Arrangement = FlowerArrangement.Vase;
                UnitPrice = 0.00M;
            }
            public Flower(FlowerType type, FlowerColor color,
                    FlowerArrangement argn, decimal price)
            {
                Type = type;
                Color = color;
                Arrangement = argn;
                UnitPrice = price;
            }
        }
    }
  6. Save the file

if…else if and if…else if…else

If you use an if...else conditional statement, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:

if(Condition1) Statement1;
else if(Condition2) Statement2;

The compiler would first check Condition1. If Condition1 is true, then Statement1 would be executed. If Condition1 is false, then the compiler would check Condition2. If Condition2 is true, then the compiler would execute Statement2. Any other result would be ignored. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        if (choice == 1) type = HouseType.SingleFamily;
        else if (choice == 2) type = HouseType.Townhouse;

        Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = int.Parse(Console.ReadLine());
        if (ans == 1)
            strGarage = "Yes";
        else
            strGarage = "No";

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Does the house have an indoor garage (1=Yes/0=No)? 1

Desired House Type: SingleFamily
Has indoor garage?  Yes
Press any key to continue . . .

Here is another example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Does the house have an indoor garage (1=Yes/0=No)? 6

Desired House Type: Townhouse
Has indoor garage?  No
Press any key to continue . . .

Notice that only two conditions are evaluated. Any condition other than these two is not considered. Because there can be other alternatives, the C# language provides an alternate else as the last resort. Its formula is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else
    Statement-n;
if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else if(Condition3)
    Statement3;
else
    Statement-n;

The compiler will check the first condition. If Condition1 is true, it executes Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        if (choice == 1)
            type = HouseType.SingleFamily;
        else if (choice == 2)
            type = HouseType.Townhouse;
        else if (choice == 3)
            type = HouseType.Condominium;
        else
            type = HouseType.Unknown;

        Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = int.Parse(Console.ReadLine());
        if (ans == 1)
            strGarage = "Yes";
        else
            strGarage = "No";

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (1=Yes/0=No)? 0

Desired House Type: Condominium
Has indoor garage?  No
Press any key to continue . . .
 

Previous Copyright © 2006 FunctionX, Inc. Next