Home

Conditional Switches

 

if 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;

public class Exercise
{
    static int Main()
    {
        var Number1 = 0;
        var Number2 = 0;
        var Maximum = 0;
        var Num1 = "";
        var 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();
        return 0;
    }
}
 

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 Conditional Switches

  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;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    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
        }
    
        public 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
}

public class Exercise
{
    static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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)? ");
        var Answer = int.Parse(Console.ReadLine());
        if (Answer == 1)
            Garage = "Yes";
        else
            Garage = "No";

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

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
}

public class Exercise
{
    public static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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)? ");
        var Answer = int.Parse(Console.ReadLine());
        if (Answer == 1)
            Garage = "Yes";
        else
            Garage = "No";

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

	return 0;
    }
}

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 . . .
 

Case Switches

 

Introduction

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
}
In C++, you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs. To avoid it, C# requires code interruption at the end of every case. This interruption is done using the break keyword.

The expression to examine in a case statement is an integer. Since a member of an enumerator (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

using System;

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

public class Exercise
{
    public static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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());

        switch (Choice)
        {
            case 1:
                Type = HouseType.SingleFamily;
                break;

            case 2:
                Type = HouseType.Townhouse;
                break;

            case 3:
                Type = HouseType.Condominium;
                break;
        }

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

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

	return 0;
    }
}

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
    default:
         Other-Possibility;
	break;
}
In C++, the default section doesn't need a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.

Therefore another version of the program above would be

using System;

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

public class Exercise
{
    public static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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());

        switch (Choice)
        {
            case 1:
                Type = HouseType.SingleFamily;
                break;

            case 2:
                Type = HouseType.Townhouse;
                break;

            case 3:
                Type = HouseType.Condominium;
                break;

            default:
                Type = HouseType.Unknown;
                break;
        }

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

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

	return 0;
    }
}

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? 8
Does the house have an indoor garage (1=Yes/0=No)? 2

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

Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases. Here is an example:

using System;

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

public class Exercise
{
    public static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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());

        switch (Choice)
        {
            case 1:
                Type = HouseType.SingleFamily;
                break;

            case 2:
                Type = HouseType.Townhouse;
                break;

            case 3:
                Type = HouseType.Condominium;
                break;

            default:
                Type = HouseType.Unknown;
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        var Answer = char.Parse(Console.ReadLine());
        switch (Answer)
        {
            case 'y':
                Garage = "Yes";
                break;

            case 'Y':
                Garage = "Yes";
                break;

            case 'n':
                Garage = "No";
                break;

            case 'N':
                Garage = "No";
                break;

            default:
                Garage = "Not Specified";
                break;
        }

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

        return 0;
    }
}

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 (y/n)? y

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

Practical LearningPractical Learning: Using Conditional Switches

  1. To create a new class, in the Solution Explorer, right-click the project name, position the mouse on Add and click Class...
  2. Set the Name of the class to OrderProcessing and click Add
  3. Complete the OrderProcessing.cs file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace FlowerShop2
    {
        class OrderProcessing
        {
            public Flower FlowerOrder;
            public int Quantity;
    
            public OrderProcessing()
            {
                FlowerOrder = new Flower();
            }
    
            public decimal GetTotalPrice()
            {
                return Quantity * FlowerOrder.UnitPrice;
            }
    
            public void GetFlowerType()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Type of Flower Order");
                Console.WriteLine("1. Roses");
                Console.WriteLine("2. Lilies");
                Console.WriteLine("3. Daisies");
                Console.WriteLine("4. Carnations");
                Console.WriteLine("5. Live Plant");
                Console.WriteLine("6. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Type = FlowerType.Roses;
                        break;
                    case 2:
                        FlowerOrder.Type = FlowerType.Lilies;
                        break;
                    case 3:
                        FlowerOrder.Type = FlowerType.Daisies;
                        break;
                    case 4:
                        FlowerOrder.Type = FlowerType.Carnations;
                        break;
                    case 5:
                        FlowerOrder.Type = FlowerType.LivePlant;
                        break;
                    default:
                        FlowerOrder.Type = FlowerType.Mixed;
                        break;
                }
            }
    
            public void GetFlowerColor()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Color");
                Console.WriteLine("1. Red");
                Console.WriteLine("2. White");
                Console.WriteLine("3. Yellow");
                Console.WriteLine("4. Pink");
                Console.WriteLine("5. Orange");
                Console.WriteLine("6. Blue");
                Console.WriteLine("7. Lavender");
                Console.WriteLine("8. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Color = FlowerColor.Red;
                        break;
                    case 2:
                        FlowerOrder.Color = FlowerColor.White;
                        break;
                    case 3:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 4:
                        FlowerOrder.Color = FlowerColor.Pink;
                        break;
                    case 5:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 6:
                        FlowerOrder.Color = FlowerColor.Blue;
                        break;
                    case 7:
                        FlowerOrder.Color = FlowerColor.Lavender;
                        break;
                    default:
                        FlowerOrder.Color = FlowerColor.Mixed;
                        break;
                }
            }
    
            public void GetFlowerArrangement()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Type of Arrangement");
                Console.WriteLine("1. Bouquet");
                Console.WriteLine("2. Vase");
                Console.WriteLine("3. Basket");
                Console.WriteLine("4. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Arrangement = FlowerArrangement.Bouquet;
                        break;
                    case 2:
                        FlowerOrder.Arrangement = FlowerArrangement.Vase;
                        break;
                    case 3:
                        FlowerOrder.Arrangement = FlowerArrangement.Basket;
                        break;
                    default:
                        FlowerOrder.Arrangement = FlowerArrangement.Any;
                        break;
                }
            }
    
            public void ProcessOrder()
            {
                GetFlowerType();
                GetFlowerColor();
                GetFlowerArrangement();
    
                Console.Write("Enter the Unit Price: ");
                FlowerOrder.UnitPrice = decimal.Parse(Console.ReadLine());
    
                Console.Write("Enter Quantity:       ");
                Quantity = int.Parse(Console.ReadLine());
            }
    
            public void ShowOrder()
            {
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
                Console.WriteLine("Flower Type:  {0}", FlowerOrder.Type);
                Console.WriteLine("Flower Color: {0}", FlowerOrder.Color);
                Console.WriteLine("Arrangement:  {0}", FlowerOrder.Arrangement);
                Console.WriteLine("Price:        {0:C}", FlowerOrder.UnitPrice);
                Console.WriteLine("Quantity:     {0}", Quantity);
                Console.WriteLine("Total Price:  {0:C}", GetTotalPrice());
                Console.WriteLine("=======================");
            }
        }
    }
  4. Access the Program.cs file and complete it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace FlowerShop2
    {
        class Program
        {
            static void Main()
            {
                OrderProcessing order = new OrderProcessing();
    
                order.ProcessOrder();
                Console.WriteLine();
    
                order.ShowOrder();
                Console.WriteLine();
            }
        }
    }
  5. Execute the application and test it. Here is an example:
     
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 4
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 7
    Enter the Type of Arrangement
    1. Bouquet
    2. Vase
    3. Basket
    4. Mixed
    Your Choice: 3
    Enter the Unit Price: 45.85
    Enter Quantity:       3
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  Carnations
    Flower Color: Lavender
    Arrangement:  Basket
    Price:        $45.85
    Quantity:     3
    Total Price:  $137.55
    =======================
    
    Press any key to continue . . .
  6. Close the DOS window

Combining Cases

Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement. Here is an example:

using System;

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

public class Exercise
{
    public static int Main()
    {
        var Type = HouseType.Unknown;
        var Choice = 0;
        var Garage = "";

        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());

        switch (Choice)
        {
            case 1:
                Type = HouseType.SingleFamily;
                break;

            case 2:
                Type = HouseType.Townhouse;
                break;

            case 3:
                Type = HouseType.Condominium;
                break;

            default:
                Type = HouseType.Unknown;
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        var Answer = char.Parse(Console.ReadLine());
        switch (Answer)
        {
            case 'y':
            case 'Y':
                Garage = "Yes";
                break;

            case 'n':
            case 'N':
                Garage = "No";
                break;

            default:
                Garage = "Not Specified";
                break;
        }

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

        return 0;
    }
}

This would produce:

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 (y/n)? Y

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

Using Enumerations

One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements. Here is an example:

using System;

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

public class Exercise
{
    public static int Main()
    {
        var PropertyType = "";
        var Choice = 0;
        var Garage = "";

        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());

        switch ((HouseType)Choice)
        {
            case HouseType.SingleFamily:
                PropertyType = "Single Family";
                break;

            case HouseType.Townhouse:
                PropertyType = "Townhouse";
                break;

            case HouseType.Condominium:
                PropertyType = "Condominium";
                break;

            default:
                PropertyType = "Unknown";
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        var Answer = char.Parse(Console.ReadLine());
        switch (Answer)
        {
            case 'y':
            case 'Y':
                Garage = "Yes";
                break;

            case 'n':
            case 'N':
                Garage = "No";
                break;

            default:
                Garage = "Not Specified";
                break;
        }

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

        return 0;
    }
}

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 (y/n)? N

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

 

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next