Home

Conditional Statements

   

if a Condition is True

 

Introduction

A conditional statement is an expression that produces a true or false result. You can use that result as you see fit. To create the expression, you use the Boolean operators we studied in the previous lesson. In the previous lesson, we saw only how to perform the operations and how to get the results, not how to use them. To use the result of a Boolean operation, the C# programming language provides some specific conditional operators.

 

ApplicationApplication: Introducing Conditional Expressions

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to ElectronicStore2
  5. Press Enter
  6. To create a new class, in the Class View, right-click ElectronicStore2 -> Add -> Class...
  7. Set the Name of the class to StoreItem and click Add
  8. Complete the StoreItem.cs file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ElectronicStore2
    {
        public enum ItemsCategories
        {
            Unknown,
            CablesAndConnectors,
            CellPhonesAndAccessories,
            Headphones,
            DigitalCameras,
            PDAsAndAccessories,
            TelephonesAndAccessories,
            TVsAndVideos,
            SurgeProtectors,
            Instructional
        }
    
        public class StoreItem
        {
            public long itemNumber;
            public string name;
            public ItemsCategories category;
            public string manufacturer;
            public string model;
            public decimal unitPrice;
    
            public StoreItem(long itmNbr = 0, string itemName = "N/A",
                             ItemsCategories kind = ItemsCategories.Unknown,
                             string make = "Unknown", string mdl = "Unspecified",
                             decimal price = 0.00M)
            {
                itemNumber = itmNbr;
                name = itemName;
                category = kind;
                manufacturer = make;
                model = mdl;
                unitPrice = price;
            }
        }
    }

Creating an if Condition

Consider the following program:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}
Condominiums
public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;

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

        Console.WriteLine("\nDesired House Type: {0}", type);
	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

Desired House Type: Unknown
Press any key to continue . . .

To check if an expression is true and use its Boolean result, you can use the if operator. Its formula is:

if(Condition) Statement;

The Condition can be the type of Boolean operation we studied in the previous lesson. That is, it can have the following formula:

Operand1 BooleanOperator Operand2

If the Condition produces a true result, then the compiler executes the Statement. If the statement to execute is short, you can write it on the same line with the condition that is being checked. 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;

        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;

        Console.WriteLine("\nDesired House Type: {0}", type);
	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

Desired House Type: SingleFamily
Press any key to continue . . .

If the Statement is too long, you can write it on a different line than the if condition. 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;

        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;

        Console.WriteLine("\nDesired House Type: {0}", type);
	return 0;
    }
}

You can also write the Statement on its own line even if the statement is short enough to fit on the same line with the Condition.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket "{" and a closing curly bracket "}". 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;

        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;
            Console.WriteLine("\nDesired House Type: {0}", type);
        }
	return 0;
    }
}

If you omit the brackets, only the statement that immediately follows the condition would be executed. As an alternative to create an if conditional statement, right-click the section where you want to add the code and click Code Snippet... Double-click Visual C#. In the list, double-click if:

if

Just as you can create one if condition, you can write more than one. Here are examples:

using System;

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

public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;

        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;
        if (choice == 2)
            type = HouseType.Townhouse;
        if (choice == 3)
            type = HouseType.Condominium;

        Console.WriteLine("\nDesired House Type: {0}", type);
	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

Desired House Type: Condominium
Press any key to continue . . .

ApplicationApplication: Using the Simple if Condition

  1. To create a new file, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Code File
  3. Change the file name to ElectronicStore and press Enter
  4. In the empty document, type the following:
    using System;
    using ElectronicStore2;
    
    public class Store
    {
        StoreItem CreateStoreItem()
        {
            int? category = null;
            StoreItem sItem = new StoreItem();
    
            Console.Title = "Electronic Super Store";
            Console.WriteLine("=-= Nearson Electonics =-=");
            Console.WriteLine("******* Store Items ******");
            Console.WriteLine(
            "To create a store item, enter its information");
            Console.Write("Item Number: ");
            sItem.itemNumber = long.Parse(Console.ReadLine());
            Console.WriteLine("Category");
            Console.WriteLine("1.  Unknown/Miscellaneous");
            Console.WriteLine("2.  Cables and Connectors");
            Console.WriteLine("3.  Cell Phones and Accessories");
            Console.WriteLine("4.  Headphones");
            Console.WriteLine("5.  Digital Cameras");
            Console.WriteLine("6.  PDAs and Accessories");
            Console.WriteLine("7.  Telephones and Accessories");
            Console.WriteLine("8.  TVs and Videos - Plasma / LCD");
            Console.WriteLine("9.  Surge Protector");
            Console.WriteLine("10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
            Console.Write("Your Choice? ");
            category = int.Parse(Console.ReadLine());
    
            if (category == 1)
                sItem.category = ItemsCategories.Unknown;
            if (category == 2)
                sItem.category = ItemsCategories.CablesAndConnectors;
            if (category == 3)
                sItem.category = ItemsCategories.CellPhonesAndAccessories;
            if (category == 4)
                sItem.category = ItemsCategories.Headphones;
            if (category == 5)
                sItem.category = ItemsCategories.DigitalCameras;
            if (category == 6)
                sItem.category = ItemsCategories.PDAsAndAccessories;
            if (category == 7)
                sItem.category = ItemsCategories.TelephonesAndAccessories;
            if (category == 8)
                sItem.category = ItemsCategories.TVsAndVideos;
            if (category == 9)
                sItem.category = ItemsCategories.SurgeProtectors;
            if (category == 10)
                sItem.category = ItemsCategories.Instructional;
    
            Console.Write("Make:        ");
            sItem.manufacturer = Console.ReadLine();
            Console.Write("Model:       ");
            sItem.model = Console.ReadLine();
            Console.Write("Unit Price:  ");
            sItem.unitPrice = decimal.Parse(Console.ReadLine());
    
            return sItem;
        }
    
        void DescribeStoreItem(StoreItem item)
        {
            Console.Title = "Electronic Super Store";
            Console.WriteLine("=-= Nearson Electonics =-=");
            Console.WriteLine("******* Store Items ******");
            Console.WriteLine("Store Item Description");
            Console.WriteLine("Item Number:   {0}", item.itemNumber);
            Console.WriteLine("Category:      {0}", item.category);
            Console.WriteLine("Make:          {0}", item.manufacturer);
            Console.WriteLine("Model:         {0}", item.model);
            Console.WriteLine("Unit Price:    {0:C}", item.unitPrice);
        }
    
        public static int Main()
        {
            Store st = new Store();
            StoreItem saleItem = st.CreateStoreItem();
    
            Console.Clear();
    
            st.DescribeStoreItem(saleItem);
            
            System.Console.ReadKey();
            return 0;
        }
    }
  5. To execute, on the main menu, click Debug -> Steart Debugging
  6. When requested, enter the Item Number as 972485 and press Enter
  7. For the choice of the category, enter 5 and press Enter
  8. For the make, enter Canon and press Enter
  9. For the model, type PowerShot SX20IS and press Enter
  10. For the unit price, type 369.00 and press Enter
     
    =-= Nearson Electonics =-=
    ******* Store Items ******
    To create a store item, enter its information
    Item Number: 972485
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 5
    Make:        Canon
    Model:       PowerShot SX20IS
    Unit Price:  369.00
    Digital Camera
  11. Press Enter:
    =-= Nearson Electonics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   972485
    Category:      DigitalCameras
    Make:          Canon
    Model:         PowerShot SX20IS
    Unit Price:    $369.00
    Press any key to continue . . .

if...else

Here is an example of what we learned in the previous section:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}
Single Family
public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;

        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;
        if (choice == 2)
            type = HouseType.Townhouse;
        if (choice == 3)
            type = HouseType.Condominium;

        Console.WriteLine("\nDesired House Type: {0}", type);

        if (type == HouseType.SingleFamily)
            Console.WriteLine("\nDesired House Matched");

	return 0;
    }
}

If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. As we saw in the previous section, any other result would be ignored. To address an alternative to an if condition, you can use the else condition. The formula to follow is:

if(Condition)
    Statement1;
else
    Statement2;

Once again, the Condition can be a Boolean operation like those we studied in the previous lesson. If the Condition is true, then the compiler would execute Statement1. If the Condition is false, then the compiler would execute Statement2. Here is an example:

using System;

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

public class Program
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;

        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;
        if (choice == 2)
            type = HouseType.Townhouse;
        if (choice == 3)
            type = HouseType.Condominium;

        Console.WriteLine("\nDesired House Type: {0}", type);

        if (type == HouseType.SingleFamily)
            Console.WriteLine("Desired House Matched");
        else
            Console.WriteLine("No House Desired");

	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

Desired House Type: SingleFamily
Desired House Matched
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

Desired House Type: Townhouse
No House Desired
Press any key to continue . . .

ApplicationApplication: Using the if...else Condition

  1. To use the if...else condition, change the ElectronicStore.cs file as follows:
    using System;
    using ElectronicStore2;
    
    public class Store
    {
        StoreItem CreateStoreItem()
        {
            int? category = null;
            decimal  itemPrice = 0m;
            StoreItem sItem = new StoreItem();
    
            Console.Title = "Electronic Super Store";
            Console.WriteLine("=-= Nearson Electonics =-=");
            Console.WriteLine("******* Store Items ******");
            Console.WriteLine(
            "To create a store item, enter its information");
            Console.Write("Item Number: ");
            sItem.itemNumber = long.Parse(Console.ReadLine());
            Console.WriteLine("Category");
            Console.WriteLine("1.  Unknown/Miscellaneous");
            Console.WriteLine("2.  Cables and Connectors");
            Console.WriteLine("3.  Cell Phones and Accessories");
            Console.WriteLine("4.  Headphones");
            Console.WriteLine("5.  Digital Cameras");
            Console.WriteLine("6.  PDAs and Accessories");
            Console.WriteLine("7.  Telephones and Accessories");
            Console.WriteLine("8.  TVs and Videos - Plasma / LCD");
            Console.WriteLine("9.  Surge Protector");
            Console.WriteLine("10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
            Console.Write("Your Choice? ");
            category = int.Parse(Console.ReadLine());
    
            if (category == 1)
                sItem.category = ItemsCategories.Unknown;
            if (category == 2)
                sItem.category = ItemsCategories.CablesAndConnectors;
            if (category == 3)
                sItem.category = ItemsCategories.CellPhonesAndAccessories;
            if (category == 4)
                sItem.category = ItemsCategories.Headphones;
            if (category == 5)
                sItem.category = ItemsCategories.DigitalCameras;
            if (category == 6)
                sItem.category = ItemsCategories.PDAsAndAccessories;
            if (category == 7)
                sItem.category = ItemsCategories.TelephonesAndAccessories;
            if (category == 8)
                sItem.category = ItemsCategories.TVsAndVideos;
            if (category == 9)
                sItem.category = ItemsCategories.SurgeProtectors;
            if (category == 10)
                sItem.category = ItemsCategories.Instructional;
    
            Console.Write("Make:        ");
            sItem.manufacturer = Console.ReadLine();
            Console.Write("Model:       ");
            sItem.model = Console.ReadLine();
            Console.Write("Unit Price:  ");
            itemPrice = decimal.Parse(Console.ReadLine());
             
            if (itemPrice <= 0)
                sItem.unitPrice = 0.00m;
            else
                sItem.unitPrice = itemPrice;
    
            return sItem;
        }
    
        string GetItemCategory(ItemsCategories cat)
        {
            string strCategory = "Unknown";
    
            if (cat == ItemsCategories.CablesAndConnectors)
                strCategory = "Cables & Connectors";
            if (cat == ItemsCategories.CellPhonesAndAccessories)
                strCategory = "Cell Phones & Accessories";
            if (cat == ItemsCategories.Headphones)
                strCategory = "Headphones";
            if (cat == ItemsCategories.DigitalCameras)
                strCategory = "Digital Cameras";
            if (cat == ItemsCategories.PDAsAndAccessories)
                strCategory = "PDAs & Accessories";
            if (cat == ItemsCategories.TelephonesAndAccessories)
                strCategory = "Telephones & Accessories";
            if (cat == ItemsCategories.TVsAndVideos)
                strCategory = "TVs & Videos";
            if (cat == ItemsCategories.SurgeProtectors)
                strCategory = "Surge Protectors";
            if (cat == ItemsCategories.Instructional)
                strCategory = "Instructional";
    
            return strCategory;
        }
    
        void DescribeStoreItem(StoreItem item)
        {
            string strCategory = GetItemCategory(item.category);
    
            Console.Title = "Electronic Super Store";
            Console.WriteLine("=-= Nearson Electonics =-=");
            Console.WriteLine("******* Store Items ******");
            Console.WriteLine("Store Item Description");
            Console.WriteLine("Item Number:   {0}", item.itemNumber);
            Console.WriteLine("Category:      {0}", strCategory);
            Console.WriteLine("Make:          {0}", item.manufacturer);
            Console.WriteLine("Model:         {0}", item.model);
            Console.WriteLine("Unit Price:    {0:C}", item.unitPrice);
        }
    
        public static int Main()
        {
            Store st = new Store();
            StoreItem saleItem = st.CreateStoreItem();
    
            Console.Clear();
    
            st.DescribeStoreItem(saleItem);
            
            System.Console.ReadKey();
            return 0;
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Debugging
  3. When requested, enter the values as follows and press Enter after each:
     
    =-= Nearson Electonics =-=
    ******* Store Items ******
    To create a store item, enter its information
    Item Number: 992052
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 4
    Make:        Sennheiser
    Model:       HD-555
    Unit Price:  104.00
    Headphones
  4. Press Enter
    =-= Nearson Electonics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   992052
    Category:      Headphones
    Make:          Sennheiser
    Model:         HD-555
    Unit Price:    $104.00
  5. Close the DOS window and return to your programming environment

if...else Operators

 

The Ternary Operator (?:)

If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula 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

The Null-Coalescing Operator ??

Remember that, when declaring a variable of a primitive type, you can add a question mark to the data type to specify that the variable can have a nullable value. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        double? distance = null;

        Console.WriteLine();
        return 0;
    }
}

At one time, you may want to assign the value of such a variable to another variable. If the variable is holding null, it means it does not have a value, so assigning to another variable would be meaningless. A solution is to first check whether the variable is currently holding null or an actual value. That is, you can ask the compiler to check whether the variable is currently null or it holds a value:

  • If the variable is holding an actual value, not null, assign its value to the new variable
  • If the variable is null, assign an alternate value (you must provide that value) to the variable

To support this, the C# language provides the null-coalescent operator: "??". The formula to use it is:

TargetVariable = OriginalVariable ?? AlternateValue;

You must have declared the OriginalVariable and it must be able to hold null, which is done by adding ? to it. You can first declare the TargetVariable or declare it when initializing it. Of course, both variables must be compatible. Here is an example of using the ?? operator:

using System;

public class Exercise
{
    public static int Main()
    {
        double? distance = null;
        double? fromTo = null;

        Console.WriteLine("Distance 1: {0}", distance);
        Console.WriteLine("Distance 2: {0}", fromTo);

        fromTo = distance ?? 135.85;

        Console.WriteLine("Distance 1: {0}", distance);
        Console.WriteLine("Distance 2: {0}", fromTo);

        Console.WriteLine();
        return 0;
    }
}

The fromTo = distance ?? 135.85; means that:

  • If the distance variable currently holds a non-null value, assign that value to the fromTo variable
  • If the distance variable currently holds null, assign the value 135.85 to it

The above code would produce:

Distance 1:
Distance 2:
Distance 1:
Distance 2: 135.85

Press any key to continue . . .

Here is another version of the program:

using System;

public class Exercise
{
    public static int Main()
    {
        double? distance = null;
        double? fromTo = null;

        Console.WriteLine("Distance 1: {0}", distance);
        Console.WriteLine("Distance 2: {0}", fromTo);
        Console.WriteLine("---------------------");

        fromTo = distance ?? 135.85;

        Console.WriteLine("Distance 1: {0}", distance);
        Console.WriteLine("Distance 2: {0}", fromTo);
        Console.WriteLine("---------------------");

        distance = 8284.26;
        fromTo = distance ?? 135.85;

        Console.WriteLine("Distance 1: {0}", distance);
        Console.WriteLine("Distance 2: {0}", fromTo);

        Console.WriteLine();
        return 0;
    }
}

This time, the program would produce:

Distance 1:
Distance 2:
---------------------
Distance 1:
Distance 2: 135.85
---------------------
Distance 1: 8284.26
Distance 2: 8284.26

Press any key to continue . . .

if...else if and 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 . . .

ApplicationApplication: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No
 
 

Previous CCopyright © 2010-2016, FunctionX Next