C# Language

Conditional Statements

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…

9 min read1,891 words17 code samples

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. Application: 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 and press Enter
  5. To create a new class, in the Class View, right-click ElectronicStore2 -> Add -> Class...
  6. Set the Name of the class to StoreItem and click Add
  7. 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 ItemsCategories category; public string manufacturer; public string model; public string name; public decimal unitPrice; // An item whose characteristics are not (yet) defined public StoreItem() { itemNumber = 0; category = ItemsCategories.Unknown; manufacturer = "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 mdl, decimal price) { itemNumber = itmNbr; category = ItemsCategories.Unknown; manufacturer = make; model = mdl; name = "N/A"; unitPrice = price; } // An item that is known by its name and unit price public StoreItem(long itmNbr, string itemName, decimal price) { itemNumber = itmNbr; category = ItemsCategories.Unknown; manufacturer = "Unknown"; model = "Unspecified"; name = itemName; unitPrice = price; } // An item completely defined public StoreItem(long itmNbr, ItemsCategories kind, string make, string mdl, decimal price) { itemNumber = itmNbr; category = kind; manufacturer = make; model = mdl; unitPrice = price; } } }

Creating an if Condition#

Consider the following program:

C#
using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}
C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

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

C#
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:

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

Application: 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() { StoreItem sItem = new StoreItem(); int category; 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 start debugging, in the Solution Explorer, right-click ElectronicStore2 -> Debug -> Step Into New Instance
  6. Move the windows to make sure you can see Microsoft Visual Studio, its Locals window, and the DOS window
  7. Press F8 continually until the StoreItem.cs file receives focus
  8. In the Locals window, click the + button on this to expand it
  9. Press F8 continually and observe the default values in the Locals window until the ElectronicStore.cs file receives focus again
  10. When the Locals window shows sItem, click its + button to expand it
  11. Continue pressing F8 and observe the DOS window
  12. When requested, enter the Item Number as 972485 and press Enter
  13. Continue pressing F8 and check the DOS window
  14. For the choice of the category, enter 5 and press Enter
  15. Keep pressing F8 and observe the Locals window. Notice that the value of the Category changes only when the if condition reaches 5
  16. Keep pressing F8 until the DOS window receives focus
  17. For the make, enter Canon and press Enter
  18. Press F8 a few times (2) until the DOS window receives focus
  19. For the model, type PowerShot SX20IS and press Enter
  20. Press F8 a few times (2) until the DOS window receives focus
  21. 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
  22. Press F8 a few times
  23. When the Locals window shows saleItem, click its + button to expand it
  24. Continue pressing F8. Observe both the Locals window and the DOS window =-= 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:

C#
using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}
C#
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:

C#
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:

C#
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:

C#
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:

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

Application: 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() { StoreItem sItem = new StoreItem(); int category; decimal itemPrice = 0m; 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
  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

Previous Copyright © 2010 C# Key Next