Home

Conditional Statements: if

 

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.

 

Practical LearningPractical Learning: Introducing Conditional Expressions

  1. Start Microsoft Visual C# and create a Console Application named ElectronicStore2
  2. To create a new class, on the main menu, click Project . Add Class...
  3. Set the Name of the class to StoreItem and click Add
  4. Complete the StoreItem.cs file as follows:
     
    using System;
    
    namespace ElectronicStore2
    {
        public enum ItemsCategories
        {
            Unknown,
            CablesAndConnectors,
            CellPhonesAndAccessories,
            Headphones,
            DigitalCameras,
            PDAsAndAccessories,
            TelephonesAndAccessories,
            TVsAndVideos,
            SurgeProtectors,
            Instructional
        }
    
        class StoreItem
        {
            public long ItemNumber;
            public ItemsCategories Category;
            public string Make;
            public string Model;
            public string Name;
            public decimal UnitPrice;
    
            // An item whose characteristics are not (yet) defined
            public StoreItem()
            {
                ItemNumber = 0;
                Category = ItemsCategories.Unknown;
                Make = "Unknown";
                Model = "Unspecified";
                Name = "N/A";
                UnitPrice = 0.00M;
            }
            // An item that is known by its make, model, and unit price
            public StoreItem(long itmNbr, String make,
                       String model, decimal price)
            {
                ItemNumber = itmNbr;
                Category = ItemsCategories.Unknown;
                Make = make;
                Model = model;
                Name = "N/A";
                UnitPrice = price;
            }
            // An item that is known by its name and unit price
            public StoreItem(long itmNbr, String name, decimal price)
            {
                ItemNumber = itmNbr;
                Category = ItemsCategories.Unknown;
                Make = "Unknown";
                Model = "Unspecified";
                Name = name;
                UnitPrice = price;
            }
            // An item completely defined
            public StoreItem(long itmNbr, ItemsCategories category,
                          String make, String model, decimal price)
            {
                ItemNumber = itmNbr;
                Category = category;
                Make = make;
                Model = model;
                UnitPrice = price;
            }
        }
    }
  5. Save the file

if

Consider the following program:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}
class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;

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

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
}

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

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

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
}

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

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

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
}

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

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

If you omit the brackets, only the statement that immediately follows the condition would be executed.

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

using System;

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

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

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

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

Practical LearningPractical Learning: Using the Simple if Condition

  1. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace ElectronicStore2
    {
        class Program
        {
            static StoreItem CreateStoreItem()
            {
                StoreItem sItem = new StoreItem();
                int category;
    
                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.Make = Console.ReadLine();
                Console.Write("Model:       ");
                sItem.Model = Console.ReadLine();
                Console.Write("Unit Price:  ");
                sItem.UnitPrice = decimal.Parse(Console.ReadLine());
    
                return sItem;
            }
    
            static void DescribeStoreItem(StoreItem item)
            {
                Console.WriteLine("Store Item Description");
                Console.WriteLine("Item Number:   {0}", item.ItemNumber);
                Console.WriteLine("Category:      {0}", item.Category);
                Console.WriteLine("Make:          {0}", item.Make);
                Console.WriteLine("Model:         {0}", item.Model);
                Console.WriteLine("Unit Price:    {0:C}", item.UnitPrice);
            }
    
            static void Main()
            {
                string strTitle1 = "=-= Nearson Electonics =-=";
                string strTitle2 = "******* Store Items ******";
    
                StoreItem saleItem = CreateStoreItem();
    
                Console.WriteLine("");
                DescribeStoreItem(saleItem);
            }
        }
    }
  2. Execute the application to see the result. Here is an example:
     
    To create a store item, enter its information
    Item Number: 868264
    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? 1
    Make:        Altec Lansing
    Model:       VS4221 Computer Speakers
    Unit Price:  85.95
    
    Store Item Description
    Item Number:   868264
    Category:      Unknown
    Make:          Altec Lansing
    Model:         VS4221 Computer Speakers
    Unit Price:    $85.95
    Press any key to continue . . .
  3. Close the DOS window

if…else

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

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}
class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;

        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");
    }
}

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
}

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

        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");
    }
}

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

Practical LearningPractical Learning: Using the if...else Condition

  1. Access the Program.cs file and, to use the if...else condition, change the file as follows:
     
    using System;
    
    namespace ElectronicStore2
    {
        class Program
        {
            static StoreItem CreateStoreItem()
            {
                StoreItem sItem = new StoreItem();
                int category;
                decimal itemPrice = 0M;
    
                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.Make = 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;
            }
    
            static string GetItemCategory(ItemsCategories cat)
            {
                string category = "Unknown";
    
                if (cat == ItemsCategories.CablesAndConnectors)
                    category = "Cables & Connectors";
                if (cat == ItemsCategories.CellPhonesAndAccessories)
                    category = "Cell Phones & Accessories";
                if (cat == ItemsCategories.Headphones)
                    category = "Headphones";
                if (cat == ItemsCategories.DigitalCameras)
                    category = "Digital Cameras";
                if (cat == ItemsCategories.PDAsAndAccessories)
                    category = "PDAs & Accessories";
                if (cat == ItemsCategories.TelephonesAndAccessories)
                    category = "Telephones & Accessories";
                if (cat == ItemsCategories.TVsAndVideos)
                    category = "TVs & Videos";
                if (cat == ItemsCategories.SurgeProtectors)
                    category = "Surge Protectors";
                if (cat == ItemsCategories.Instructional)
                    category = "Instructional";
    
                return category;
            }
    
            static void DescribeStoreItem(StoreItem item)
            {
                string strCategory = GetItemCategory(item.Category);
    
                Console.WriteLine("Store Item Description");
                Console.WriteLine("Item Number:   {0}", item.ItemNumber);
                Console.WriteLine("Category:      {0}", strCategory);
                Console.WriteLine("Make           {0}", item.Make);
                Console.WriteLine("Model:         {0}", item.Model);
                Console.WriteLine("Unit Price:    {0:C}", item.UnitPrice);
            }
    
            static void Main()
            {
                string strTitle1 = "=-= Nearson Electonics =-=";
                string strTitle2 = "******* Store Items ******";
    
                Console.WriteLine(strTitle1);
                Console.WriteLine(strTitle2);
                StoreItem saleItem = CreateStoreItem();
                Console.WriteLine("");
    
                Console.WriteLine(strTitle1);
                Console.WriteLine(strTitle2);
                DescribeStoreItem(saleItem);
                Console.WriteLine("");
            }
        }
    }
  2. Execute the application to test it. Here is an example:
     
    =-= Nearson Electonics =-=
    ******* Store Items ******
    To create a store item, enter its information
    Item Number: 937494
    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:       EOS 30D
    Unit Price:  1395.95
    
    =-= Nearson Electonics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   937494
    Category:      Digital Cameras
    Make           Canon
    Model:         EOS 30D
    Unit Price:    $1,395.95
    
    Press any key to continue . . .
  3. Close the DOS window

 

 

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