© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
G. ByrneTarget C#https://doi.org/10.1007/978-1-4842-8619-7_9

9. Selection

Gerard Byrne1  
(1)
Belfast, Ireland
 

Arithmetic Operations

We learned in Chapter 8 that we could apply arithmetic operations on some variables and use the {0:D} and {0:C} type placeholders to specify the number of decimal places required in the output. We also investigated the use of less familiar arithmetic operators such as +=, -=, *=, and /=. In this chapter we will use comparison operators, some of which will look similar to arithmetic operators.

Selection

In this chapter we will learn about the very important concept of selection and its use within an application. However, the concept of selection should be familiar to us through our everyday life. Many of the things we do in everyday life require us to make decisions, and often we will be directed down one path or another. Figure 9-1 illustrates such a scenario.

A diagram exhibits two different choices as possible paths to take regarding the need for a recycle bag to go shopping.

Figure 9-1

Everyday decision using a yes-or-no scenario

In a similar manner, the programs we, and every developer, write will normally require us to make decisions. Decisions in our code will change the execution flow depending on the decision made, as shown in Figure 9-1. Figure 9-1 indicates that
  • A yes decision changes execution down the yes path.

  • A no decision changes execution down the no path.

In Figure 9-1 the execution eventually returns to a common path, Go to the shops. In programming, making decisions can be achieved in a number of ways, and we will now look at the use of the SELECTION statements within C#.

Comparison Operators

To build our program code to make decisions, we need to make use of comparison operators to construct a condition. The operators we can use are familiar mathematical expressions, for example, less than, greater than, and equal to. Table 9-1 shows the symbols used in C# for the operators.
Table 9-1

Comparison operators

Symbol

Meaning

<

<=

>

>=

==

!=

&&

||

!

Less than

Less than or equal to

Greater than

Greater than or equal to

Equal to

Not equal to

Logical AND

Logical OR

Logical NOT

It is important we fully understand that when testing if one piece of data is equal to another, we use the double equals (= =), because, as mentioned previously, a single equal symbol (=) is an assignment operation.

The primary selection constructs we will use in our C# code will be
  • if

  • if-else

  • if else if construct

  • switch

We will also look at the logical operators AND (&&), || (OR), and ! (NOT).

if Statement

The if construct is used whenever a choice has to be made between two alternative actions. The construct will enable a block of code to be executed depending upon whether or not a condition is true. If the condition is not true, it is false, and the code does not execute the block of code associated with the if statement. It just moves to the next code statement. The general format of the if construct is
      if (condition)
      {
        // perform these statements when condition is true
      }

In simple terms all we are doing with the if construct is saying "Is something true?" – is it true or is it false? So the statement

if( condition ) means if( true ).

Remember true is a bool or Boolean data type.

In most programs selection will be a key element, but for an insurance program, selection statements may include
  • Checking the maximum years of no claims a driver has and informing the user

    That the value is within the years of no claims limit and will be used – this is the true part

    Or

    To just move to the next code statement

  • Checking the maximum amount that can be charged to a credit card and informing the user

    That the insurance amount is under or equal to the credit card limit and can be processed – this is the true part

or

To just move to the next code statement

if-else Statement

The general format of the if-else construct is
      if (condition)
      {
        // perform these statements when condition is true
      }
      else
      {
        // perform these statements when condition is false
      }

In simple terms all we are doing with the if-else construct is saying "Is something true or is it false?" – is it true or is it false? So the statement

if( condition ) means if( true ).

else means it is not true – it is false.

Remember false is also a bool or Boolean data type.

The else part of the if-else construct may be omitted depending on requirements, but if it is omitted, it becomes an if statement, which is what we looked at first.

Using the same insurance program criteria as we had in the preceding if statement, we can see how the if-else construct could be applied. The program selection statements may include
  • Checking the maximum years of no claims a driver has and informing the user that

    The value is within the years of no claims limit and will be used – this is the true part.

    or

    The value is over the years of no claims limit and will be reduced to 10 years – this is the else part, the false part.

  • Checking the maximum amount that can be charged to a credit card and informing the user that

    The insurance amount is under or equal to the credit card limit and can be processed.

    or

    The insurance amount is over the credit card limit and the user will need to call the company to give additional information.

The if-else statement is used to make a selection within a program, and the following points are important in understanding the format of the if-else statement:
  • The if statement will test if a particular condition statement is true, for example:

      if (yearsofnoclaims > 10)
  • If the condition is true, then the program will execute a block of code within the curly braces following it, for example:

      if (yearsofnoclaims > 10)
      {
        // This block of code will be executed if the
        // yearsofnoclaims is greater than 10
      }
  • If the condition is false, then the program will execute a different block of code, the else part, that handles a false condition executed when the statement is not true, for example:

      if (yearsofnoclaims > 10)
      {
        // This block of code will be executed if the
        // yearsofnoclaims is greater than 10
      }
      else
      {
        // This block of code will be executed if the
        // yearsofnoclaims is
        // less than or equal to 10
      }
  • It is essential that the two different blocks of code are clearly indicated, and to ensure this, we use the curly braces:

    { opening (left) curly brace

    } closing (right) curly brace

  • The two different blocks of code are separated using the else keyword:

      if (yearsofnoclaims > 10)
      {
        BLOCK ONE
       // This block of code will be executed if the
       // yearsofnoclaims is greater than 10
      }
      else
      {
        BLOCK TWO
       // This block of code will be executed if the
       // yearsofnoclaims is less than or equal to 10
      }

switch Statement

A switch statement can have a number of advantages over the equivalent if-else statements including being easier to
  • Read

  • Debug

  • Maintain

In using a switch construct, we will have multiple cases, and the matching case will be the one that will have its code executed. Switch also has some disadvantages depending on the version of C# we use. From C# 7.0 we can use pattern matching, but for now we will concentrate on the switch statement for C# 6 or earlier where the matching expression uses the data types char, string, and bool, an integral numeric type, or an enum type.

The general format of the switch construct is
      switch (expression)
      {
        case 1:
          {
            statements;
            break;
          }
        case 2:
          {
            statements;
            break;
          }
        default:
          {
            statements;
            break;
          }
          break;
      } // End of switch statement
We will now use the same insurance program criteria as used in the preceding if and if-else constructs and explore how the switch construct could be applied. The program selection statements may include
  • Checking the maximum years of no claims a driver has and informing the user that
    • If the value is 0 years, the discount is 0%.

    • If the value is 5 years, the discount is 5%.

    • If the value is 10 years, the discount is 10%.

As a switch statement, this would be
      switch (years_of_no_claims)
      {
        case 0:
          {
            discount = 0.00;
            break;
          }
        case 5:
          {
            discount = 5.00;
            break;
          }
        case 10:
          {
            discount = 10.00;
            break;
          }
        default:
          {
            discount = 0.00;
            break;
          }
      } // End of switch statement

Let's code some C# and build our programming muscle.

The if Construct

We will now use the if construct that has one block of code, between the curly braces, that is executed if the condition inside the brackets evaluates as Boolean true. If the condition evaluates to Boolean false, then, with the if construct, there is no other block of code associated with it, so the next line in the program after the close curly brace is executed. The evaluation to Boolean true would be equivalent to the area highlighted by the green dotted rectangle in Figure 9-2, the pathway to the left.

A diagram exhibits two different choices as possible paths to take regarding the need for a recycle bag to go shopping.A diagram exhibits two different choices as possible paths to take regarding the need for a recycle bag to go shopping.

Figure 9-2

The Boolean true section

We should use the same solution that we created for the earlier chapters, as we will still be able to see the code we have written for the previous chapters. The approach of keeping all our separate projects in one solution is a good idea while studying this book and coding the examples.

This chapter, while concentrating on selection, will use an insurance quote example and build on our learning from the previous chapters. Now having created five projects, we should be confident with the process of creating projects inside a solution.

Add a new project to hold the code for this chapter.
  1. 1.

    Right-click the solution CoreCSharp.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose New Project.

     
  4. 4.

    Choose Console App from the listed templates that appear.

     
  5. 5.

    Click the Next button.

     
  6. 6.

    Name the project Chapter9 and leave it in the same location.

     
  7. 7.

    Click the Next button.

     
  8. 8.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher.

     
  9. 9.

    Click the Create button.

    Now we should see the Chapter9 project within the solution called CoreCSharp.

     
  10. 10.

    Right-click the project Chapter9 in the Solution Explorer panel.

     
  11. 11.

    Click the Set as Startup Project option.

     
  12. 12.

    Right-click the Program.cs file in the Solution Explorer window.

     
  13. 13.

    Choose Rename.

     
  14. 14.

    Change the name to Selection.cs, as shown in Figure 9-3.

     
  15. 15.

    Press the Enter key.

     

A zoomed section in the left panel of the Solution Explorer window exhibits the C sharp Selection dot c s entry under Chapter 9 as the renamed file.

Figure 9-3

Program.cs file renamed

  1. 16.

    Double-click the Selection.cs file to open it in the editor window.

    Now we can set up the code structure with a namespace, and inside it will be the Selection class, and inside the class will be the Main() method. The shortcut for creating the Main() method is to type svm and press the Tab key twice. We will also create a variable inside the Main() method.

     
  2. 17.

    Amend the code as shown in Listing 9-1.

     
// Program Description:    C# program to perform selection
// Author:                 Gerry Byrne
// Date of creation:       01/10/2021
namespace Chapter9
{
  internal class Selection
  {
    static void Main(string[] args)
    {
      // Set up variables to be used in the quote application
      int yearsOfNoClaims;
    } // End of Main() method
  } // End of Selection class
} // End of Chapter9 namespace
Listing 9-1

Selection – setting up variables within the Main() method

  1. 18.

    Amend the code to request user input and then convert it to an int, as in Listing 9-2.

     
      // Set up variables to be used in the quote application
      int yearsOfNoClaims;
      /* Read the user input and convert it to an int */
      Console.WriteLine("How many full years of no claims does the driver have? ");
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
    } // End of Main() method
  } // End of Selection class
} // End of Chapter9 namespace
Listing 9-2

Request user input and convert from string to int

We will now add code that will

  • Check if the number of years of no claims is greater than 10:

  • If this is true, execute some code.

  • Otherwise, move to the next set of code lines.

  1. 19.

    Amend the code, as in Listing 9-3.

     
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
      /*
      Now we will check if the years of no claims is greater
      than 10 if it is true then we execute some lines of code
      which exist between the curly braces, else the program
      just moves to the next code line which is to read a key
      */
      if (yearsOfNoClaims > 10)
      {
       /*
       This block of code will be executed if the
       yearsOfNoClaims is more than 10
       */
        Console.WriteLine();
        Console.WriteLine("Years of no claims is more than 10");
      }
    } // End of Main() method
  } // End of Selection class
} // End of Chapter9 namespace
Listing 9-3

Use the if construct to check if value is greater than 10

  1. 20.

    Click the File menu.

     
  2. 21.

    Choose Save All.

     
  3. 22.

    Click the Debug menu.

     
  4. 23.

    Choose Start Without Debugging.

     
  5. 24.

    Type 10 as the number of full years of no claims.

     
  6. 25.

    Press the Enter key.

    Figure 9-4 shows the console window with no additional data after the 10, as the code has evaluated that 10 is not greater than (>) 10, so it skips the if block of code and moves to the next line of code after the closing curly brace, which is the end of the code.

     

A console window depicts a skipped if block where 10 is the lone entry for the number of full years of no claims a driver has.

Figure 9-4

If block skipped

  1. 26.

    Press the Enter key to close the console window.

     
  2. 27.

    Click the Debug menu.

     
  3. 28.

    Choose Start Without Debugging.

    The console window will appear and ask the question.

     
  4. 29.

    Type 20 and press the Enter key.

    The console window will appear as shown in Figure 9-5.

     

A console window depicts the execution of an if block with the years of no claims is more than 10 entry for 20.

Figure 9-5

If block executed

The code has evaluated that 20 is greater than (>) 10 so it executes the if block of code and then it moves to the next line of code, which is the end of the code.
  1. 30.

    Press the Enter key to close the console window.

     

The if-else Construct

We will now use the if-else construct , which is an extension of the if construct we have just used. In the if construct, we had one block of code, between the curly braces, that was executed when the condition inside the brackets evaluated to true. When the condition evaluated to false, the block of code was passed over, and the next line in the program was executed. Now, in the if-else construct, there will be a second block of code, with its own set of curly braces. This second block of code will be executed when the condition evaluates as false. This would be the equivalent to the area highlighted by the red dotted rectangle in Figure 9-6, the right-hand pathway.

A diagram exhibits the highlighted choice of checking that the recyclable shopping bag is large enough instead of picking one up from the cupboard to go shopping.

Figure 9-6

The Boolean false section

  1. 31.

    Amend the code, as in Listing 9-4, to add the else part of the construct.

     
      if (yearsOfNoClaims > 10)
      {
        /*
        This block of code will be executed if the
        yearsofnoclaims is more than 10
        */
        Console.WriteLine("Years of no claims is more than 10");
      }// End of true block of code in the if construct
      else
      {
      /*
      This block of code will be executed if the yearsofnoclaims
      is not more than 10. We need to be careful when we are
      dealing with boundaries and in this example we should
      realise that the >10 means 11, 12, 13 etc. The not greater
      than 10 then means 10, 9, 8 etc. In other words, 10 is
      included in the else part. We could also use >= 10 if we
      wanted 10 to be included in the true section
        */
        Console.WriteLine("Years of no claims is less than " +
          "or equal to 10");
      } // End of false block of code in the if construct
    } // End of Main() method
Listing 9-4

Use the if-else construct to check if value is greater than 10

  1. 32.

    Click the File menu.

     
  2. 33.

    Choose Save All.

     
  3. 34.

    Click the Debug menu.

     
  4. 35.

    Choose Start Without Debugging.

     
  5. 36.

    Type 20 as the number of full years of no claims.

    Figure 9-7 shows the console window, and we can see that the true block of code has been executed.

     

A console window depicts the execution of a true block with the years of no claims is more than 10 entry for 20.

Figure 9-7

If block executed – this is the true part

  1. 37.

    Press the Enter key to close the console window.

     
  2. 38.

    Click the Debug menu.

     
  3. 39.

    Choose Start Without Debugging.

     
  4. 40.

    Type 10 as the number of full years of no claims.

    Figure 9-8 shows the console window, and we can see that the false, else, block of code has been executed.

     

A console window depicts an executed false block with the years of no claims being less than or equal to 10 entry for 10.

Figure 9-8

If block skipped – this is the false part

  1. 41.

    Press the Enter key to close the console window.

     

The if else if Construct

The if-else construct we have used has two blocks of code, one for the Boolean true and the other for the Boolean false. However, what would happen if we had other choices when the first condition was not true? Well, the C# language provides us with a solution, which is an extension of the if-else construct. The if part of the construct can be followed by an else if statement . The general format will be
    if (first expression is true)
    {
        /*
          This block of code will be executed if the first
          expression is true
        */
      }
    else if (second expression is true)
    {
        /*
          This block of code will be executed if the second
          expression is true
        */
    }
    else if (third expression is true)
    {
        /*
          This block of code will be executed if the third
          expression is true
        */
    }
    else
    {
        /*
          This block of code will be executed if the first
          expression, second expression and third expression
          are all false
        */
    }
  1. 42.

    Amend the code, as in Listing 9-5, to add the else if parts of the construct, replacing the existing else code block.

     
      if (yearsOfNoClaims > 10)
      {
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 10
       */
        Console.WriteLine("Years of no claims is more than 10");
      }// End of true block of code in the if construct
      else if (yearsOfNoClaims > 8)
      {
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 8 which means 9, 10, 11,
       12 etc. However, if yearsofnoclaims is 11, 12 etc it
       will have been detected in the yearsofnoclaims > 10
       block so really it will only be the 9 and 10 that will
       be detected in this block
       */
      Console.WriteLine("Years of no claims is either 9 or 10");
      } // End of first false block of code in the if construct
      else if (yearsOfNoClaims > 6)
      {
       /*
       This block of code will be executed if the yearsofnoclaims
       is more than 6 which means 7, 8, 9, 10 etc. However,
       if yearsofnoclaims is 9, 10 etc it will have been
       detected in the yearsofnoclaims > 8 block so really it
       will only be the 7 and 8 that will be detected in
       this block
       */
        Console.WriteLine("Years of no claims is either 7 or 8");
      } // End of second false block of code in the if construct
      else if (yearsOfNoClaims > 4)
      {
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 4 which means 5, 6, 7,
       8 etc. However, if yearsofnoclaims is 7, 8 etc it will
       have been detected in the yearsofnoclaims > 6 block so
       really it will only be the 5 and 6 that will be detected
       in this block
       */
        Console.WriteLine("Years of no claims is either 5 or 6");
      } // End of third false block of code in the if construct
      else if (yearsOfNoClaims > 2)
      {
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 2 which means 3, 4, 5,
       6 etc. However, if yearsofnoclaims is 5, 6 etc it will
       have been detected in the yearsofnoclaims > 4 block so
       really it will only be the 3 and 4 that will be detected
       in this block
       */
        Console.WriteLine("Years of no claims is either 3 or 4");
      } // End of fourth false block of code in the if construct
      else
      {
       /*
        This block of code will be executed if the
       yearsofnoclaims is not more than 2.
       For this block of code to be executed none of the
       conditions above must have been true (and none of the
       blocks of code were executed)
       */
        Console.WriteLine("Years of no claims is 2, 1, 0 " +
         " or indeed a negative number of years " +
         " because of a penalty being enforced on our policy");          } // End of final false block of code in the if construct
} // End of Main() method
  } // End of Selection class
} // End of Chapter9 namespace
Listing 9-5

Adding the else if parts of the if-else construct

  1. 43.

    Click the File menu.

     
  2. 44.

    Choose Save All.

     
  3. 45.

    Click the Debug menu.

     
  4. 46.

    Choose Start Without Debugging.

    The console window will appear and ask the question. Now we can try the values 10, 8, 6, 4, and 2, which will test the five else blocks. We will start with 10.

     
  5. 47.

    Type 10 as the number of full years of no claims.

     
  6. 48.

    Press the Enter key.

    Figure 9-9 shows the console window and we can see that the first else if block of code has been executed.

     

A console window depicts the execution of else block 1 with the years of no claims is either 9 or 10 entry for 10.

Figure 9-9

First else if block executed

  1. 49.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 50.

    Click the Debug menu.

     
  3. 51.

    Choose Start Without Debugging.

     
  4. 52.

    Type 8 as the number of full years of no claims.

     
  5. 53.

    Press the Enter key.

    Figure 9-10 shows the console window and we can see that the second else if block of code has been executed.

     

A console window depicts the execution of else block 2 with the years of no claims is either 7 or 8 entry for 8.

Figure 9-10

Second else if block executed

  1. 54.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 55.

    Click the Debug menu.

     
  3. 56.

    Choose Start Without Debugging.

     
  4. 57.

    Type 6 as the number of full years of no claims.

     
  5. 58.

    Press the Enter key.

    Figure 9-11 shows the console window and we can see that the third else if block of code has been executed.

     

A console window depicts the execution of else block 3 with the years of no claims is either 5 or 6 entry for 6.

Figure 9-11

Third else if block executed

  1. 59.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 60.

    Click the Debug menu.

     
  3. 61.

    Choose Start Without Debugging.

     
  4. 62.

    Type 4 as the number of full years of no claims.

     
  5. 63.

    Press the Enter key.

    Figure 9-12 shows the console window and we can see that the fourth else if block of code has been executed.

     

A console window depicts the execution of else block 4 with the years of no claims is either 3 or 4 entry for 4.

Figure 9-12

Fourth else if block executed

  1. 64.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 65.

    Click the Debug menu.

     
  3. 66.

    Choose Start Without Debugging.

     
  4. 67.

    Type 2 as the number of full years of no claims.

     
  5. 68.

    Press the Enter key.

    Figure 9-13 shows the console window and we can see that the fifth else if block of code has been executed.

     

A console window depicts the execution of else block 5 with an entry that starts with the years of no claims is either 2, 1, 0.

Figure 9-13

Fifth else if block executed

  1. 69.

    Press the Enter key to close the console window.

     
As we can see, the code works fine, and our test values have shown the correct blocks of code were executed. If we formatted the code differently, we could see why the if else if construct is often called the if else ladder. The code moves into the right for each section as shown in Figure 9-14.

A 26-line code constructed as an if-else ladder. On its right is a text that reads, There are better ways to do this in a large font.

Figure 9-14

If else ladder

So do we think the code is OK because it executes properly?

We might say yes, but that would mean we are only concerned about the code execution. Let's think differently and consider code readability, maintainability, and efficiency. These aspects of code also play an important role in the code development process. It is not aways about our view; there may be others involved in the process. We must take a wider view of code development and not just think about our own small worldview. By thinking wider, we will think about others who are required to read our code, those who will have to maintain our code, and those who will use the code.

The previous code can indeed be made better in terms of readability and maintainability, by using another selection construct called the switch construct. It is important for us to understand that, in terms of efficiency, the switch construct is not always faster than the if else if construct.

The switch Construct

The switch construct is an alternative to the if-else construct we have just used in our code. As we read earlier, the general format of the switch construct is
      switch (expression)
      {
        case 1:
          {
            statements;
            break;
          }
        case 2:
          {
            statements;
            break;
          }
        default:
          {
            statements;
            break;
          }
          break;
      } // End of switch statement
We will now apply this format to the if else if construct code we have just written. To do this we will create a new class in the project and make this new class the startup class.
  1. 1.

    Right-click the Chapter9, Selection, project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class Switch.cs.

     
  5. 5.

    Click the Add button.

    The Switch class code will appear in the editor window and will be similar to Listing 9-6. Remember using System is intrinsic and may not be displayed.

     
using System;
namespace Chapter9
{
  internal class Switch
  {
  } // End of Switch class
} // End of Chapter9 namespace
Listing 9-6

Class template when adding a class

As the Main() method has not been created automatically, we will create a Main() method within the class by typing svm and pressing the Tab key twice. We will also delete the unwanted imports.
  1. 6.

    Amend the code as in Listing 9-7.

     
using System;
namespace Chapter9
{
  internal class Switch
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of Switch class
} // End of Chapter9 namespace
Listing 9-7

Main() method added and unused imports removed

Now we need to set this class as the startup class for the project.
  1. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  2. 8.

    Choose Properties from the pop-up menu.

     
  3. 9.

    Choose the Chapter9.Switch class in the Startup object drop-down list, as shown in Figure 9-15.

     

A zoomed Startup object section in the Solution Explorer panel exhibits a highlighted Chapter 9 dot Switch class from the drop-down list.

Figure 9-15

Changing the startup class in the C# project

  1. 10.

    Close the Properties window.

    Now we will add the variables that will be used in our code. Firstly, we will set up a variable for the years of no claims and then add the code that will ask the user for input, read the console input, and convert it to data type int. In the code there are detailed comments to help us get a full understanding of the code.

     
  2. 11.

    Amend the code, as in Listing 9-8.

     
    static void Main(string[] args)
    {
      /*
      We will setup our variables that will be used in
      the quote application
      */
      int yearsOfNoClaims;
      /* Read the user input and convert it to an int */
      Console.WriteLine("How many full years of no claims " +
        "does the driver have? ");
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
    } // End of Main() method
Listing 9-8

Ask for user input and convert the string input to int

  1. 12.

    Amend the code , as in Listing 9-9, to add the switch construct.

     
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
     /*
     Now we will check if the years of no claims is greater
     than 10 if it is true then we execute some lines of code
     which exist between the curly braces, else the program
     just moves to the next code line which is to read a key
     */
     switch (yearsOfNoClaims)
     {
       case 11:
       case 12:
       case 13:
       case 14:
       case 15:
        /*
        This block of code will be executed if the
        yearsOfNoClaims is more than 10
        */
        Console.WriteLine("Years of no claims is more" +
          " than 10 but less than 16");
        break;
       case 9:
       case 10:
        /*
        This block of code will be executed if the
        yearsOfNoClaims is either 9 or 10
        */
        Console.WriteLine("Years of no claims is either" +
          " 9 or 10");
        break;
       case 7:
       case 8:
        /*
        This block of code will be executed if the
        yearsOfNoClaims is either 7 or 8
        */
        Console.WriteLine("Years of no claims is either 7 or 8");
        break;
       case 5:
       case 6:
        /*
        This block of code will be executed if the
        yearsOfNoClaims is either 5 or 6
        */
        Console.WriteLine("Years of no claims is either 5 or 6");
        break;
       case 3:
       case 4:
        /*
        This block of code will be executed if the
        yearsOfNoClaims is either 3 or 4
        */
        Console.WriteLine("Years of no claims is either 3 or 4");
        break;
       default:
       /*
       This block of code will be executed if the
       yearsOfNoClaims is not one of the values in the case
       statements 4 to 15. That means if the value is more than
       15 or less than 4 this block will be executed.
       We need to think, is this what we really want. Certainly
       it does not give us the same result as the if else-if
       */
       Console.WriteLine("Years of no claims is either less " +
         "than 3 or greater than 15");
       break;
      } // End of switch construct
    } // End of Main() method
  } // End of Switch class
} // End of Chapter9 namespace
Listing 9-9

The switch construct

  1. 13.

    Click the File menu.

     
  2. 14.

    Choose Save All.

     
  3. 15.

    Click the Debug menu.

     
  4. 16.

    Choose Start Without Debugging.

    The console window will appear and ask the question. Now we can try the values 15, 10, 8, 6, 4, and 2, which will test the six case blocks. We will start with 15.

     
  5. 17.

    Type 15 and press the Enter key.

    Figure 9-16 shows the console window, and we can see that the first case block of code has been executed.

     

A console window depicts an executed first case block of code via case 15 with the years of no claims being more than 10 but less than 16 entry for 15.

Figure 9-16

Switch case 15

  1. 18.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 19.

    Click the Debug menu.

     
  3. 20.

    Choose Start Without Debugging.

     
  4. 21.

    Type 10 and press the Enter key.

    Figure 9-17 shows the console window, and we can see that the second case block of code has been executed.

     

A console window depicts an executed second case block of code via case 10 with the years of no claims as either 9 or 10 entry for 10.

Figure 9-17

Switch case 10

  1. 22.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 23.

    Click the Debug menu.

     
  3. 24.

    Choose Start Without Debugging.

     
  4. 25.

    Type 8 and press the Enter key.

    Figure 9-18 shows the console window, and we can see that the third case block of code has been executed.

     

A console window depicts an executed third case block of code via case 8 with the years of no claims is either 7 or 8 entry for 8.

Figure 9-18

Switch case 8

  1. 26.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 27.

    Click the Debug menu.

     
  3. 28.

    Choose Start Without Debugging.

     
  4. 29.

    Type 6 and press the Enter key.

    Figure 9-19 shows the console window, and we can see that the fourth case block of code has been executed.

     

A console window depicts an executed fourth case block of code via case 6 with the years of no claims is either 5 or 6 entry for 6.

Figure 9-19

Switch case 6

  1. 30.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 31.

    Click the Debug menu.

     
  3. 32.

    Choose Start Without Debugging.

     
  4. 33.

    Type 4 and press the Enter key.

    Figure 9-20 shows the console window, and we can see that the fifth case block of code has been executed.

     

A console window depicts an executed fifth case block of code via case 4 with the years of no claims as either 3 or 4 entry marked for 4.

Figure 9-20

Switch case 4

  1. 34.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 35.

    Click the Debug menu.

     
  3. 36.

    Choose Start Without Debugging.

     
  4. 37.

    Type 2 and press the Enter key.

    Figure 9-21 shows the console window, and we can see that the sixth case block, the default block, of code has been executed.

     

A console window depicts an executed default block via default case with the years of no claims is either less than 3 or greater than 15 entry for 2.

Figure 9-21

Switch case default

  1. 38.

    Press the Enter key to close the console window.

    The switch construct is a replacement for the if else if construct.

    As we might see, the only issue in our case construct code arises for the equivalent of yearsOfNoClaims >10:
    • In the if else if, the yearsOfNoClaims >10 handled values 11, 12, 13, 14, 15, 16, 17, etc.

    • In the switch statement, we had to individually state case 11, case 12, case 13, case 14, case 15, etc. But to do this for all values above 10 would be a long and wasteful process .

    • So we may need to think of a better way to do this. We might use an if statement in the default block to check if the value is less than 3 or greater than 15 or just use the if else if construct.

    • The case construct in C# 6 or lower does not always allow for the use of a range of numbers or even >10 as the case. The switch statement should not be used for condition checking.

     

C# 7

From C# 7 we can use a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value, true or false.

The switch Construct Using when

We will now apply this format to the code we wrote for the case construct. To do this we will create a new class in the project and make this new class the startup class .
  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class Switch7Onwards.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Create a Main() method within the class, as this was not produced automatically, and delete the unwanted imports, as in Listing 9-10.

     
namespace Chapter9
{
  internal class Switch7Onwards
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of Switch7Onwards class
} // End of Chapter9 namespace
Listing 9-10

The class with the Main() method

Now we need to set this class as the startup class for the project.
  1. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  2. 8.

    Choose Properties from the pop-up menu.

     
  3. 9.

    Choose the Chapter9.Switch7Onwards class in the Startup object drop-down list, as shown in Figure 9-22.

     

A zoomed Startup object section in the Solution Explorer panel exhibits a highlighted Chapter 9 dot Switch 7 onwards class from the drop-down list.

Figure 9-22

Changing the startup class in the C# project

  1. 10.

    Close the Properties window.

     
  2. 11.

    Amend the code, as in Listing 9-11, to add the code with the new when format for the first case block.

     
using System;
namespace Chapter9
{
  internal class Switch7Onwards
  {
    static void Main(string[] args)
    {
      /*
      We will setup our variables that will be used in
      the quote application
      */
      int yearsOfNoClaims;
      /* Read the user input and convert it to an int */
      Console.WriteLine("How many full years of no claims does the driver have? ");
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
      /*
      Now we will check if the years of no claims is greater
      than 10
      * if it is true then we execute some lines of code
        which exist between the curly braces, else the program
        just moves to the next code line which is to read a key
      */
      switch (yearsOfNoClaims)
      {
       case int numberOfYearsEntered when (yearsOfNoClaims > 10):
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 10
       */
      Console.WriteLine("Years of no claims is more than 10");
       break;
      } // End of switch construct
    } // End of Main() method
  } // End of Switch7Onwards class
} // End of Chapter9 namespace
Listing 9-11

First case block with the when clause

Note

The line of code that has the when clause in it tells the compiler that we want this case block to execute when the yearsOfNoClaims value is greater than 10.
  1. 12.

    Amend the code, as in Listing 9-12, to add the new when format for the second case block.

     
      Console.WriteLine("Years of no claims is more than 10");
       break;
      case int numberOfYearsEntered when (yearsOfNoClaims > 8):
       /*
       This block of code will be executed if the
       yearsofnoclaims is more than 8 which means 9, 10, 11,
       12 etc. However if yearsofnoclaims is 11, 12 etc it
       will have been detected in the case above where the
       condition  yearsofnoclaims > 10is used.
       */
      Console.WriteLine("Years of no claims is either 9 or 10");
      break;
      } //End of switch construct
    } // End of Main() method
  } // End of Switch7Onwards class
} // End of Chapter9 namespace
Listing 9-12

Second case block with the when clause

The when clause tells the compiler that we want this case block to execute when the yearsOfNoClaims value is greater than 8 and less than 11.

We will now repeat the use of the when statement for the other case elements.
  1. 13.

    Amend the code, as in Listing 9-13, to add the new format for the remaining case blocks.

     
      Console.WriteLine("Years of no claims is either 9 or 10");
        break;
      case int numberOfYearsEntered when (yearsOfNoClaims > 6):
        /*
        This block of code will be executed if the
        yearsofnoclaims is more than 6 which means 7, 8, 9,
        10 etc. However if yearsofnoclaims is 9, 10 etc it will
        have been detected in the case above where the condition
        yearsofnoclaims > 8 is used.
        */
        Console.WriteLine("Years of no claims is either 7 or 8");
        break;
      case int numberOfYearsEntered when (yearsOfNoClaims > 4):
      /*
      This block of code will be executed if the
        yearsofnoclaims is more than 4 which means 5, 6, 7,
        8 etc. However if yearsofnoclaims is 7, 8 etc it will
        have been detected in the case above where the condition
        yearsofnoclaims > 4 is used.
        */
        Console.WriteLine("Years of no claims is either 5 or 6");
        break;
      case int numberOfYearsEntered when (yearsOfNoClaims > 2):
        /*
        This block of code will be executed if the
        yearsofnoclaims is more than 2 which means 3, 4, 5,
        6 etc.. However if yearsofnoclaims is 5, 6 etc it will
        have been detected in the case above where the condition
        yearsofnoclaims > 2 is used.
        */
        Console.WriteLine("Years of no claims is either 3 or 4");
        break;
      default:
      /*
      This block of code will be executed if the
      yearsofnoclaims is not more than 2. For this block of
      code to be executed none of the conditions above must
      have been true (and none of the blocks of code were
      executed*/
      Console.WriteLine("Years of no claims is 2, 1, 0 " +
       " or indeed a negative number of years " +
       " because of a penalty being enforced on our policy");
      break;
      } // End of switch construct
    } // End of Main() method
  } // End of Switch7Onwards class
} // End of Chapter9 namespace
Listing 9-13

Completed code with all when clauses

  1. 14.

    Click the File menu.

     
  2. 15.

    Choose Save All.

     
  3. 16.

    Click the Debug menu.

     
  4. 17.

    Choose Start Without Debugging.

    The console window will appear and ask the question. Now we can try the values 15, 10, 8, 6, 4, and 2, which will test the six case blocks. We will start with 15.

     
  5. 18.

    Type 15 and press the Enter key.

    Figure 9-23 shows the console window and we can see that the first case block of code has been executed.

     

A console window depicts an entry from executing the first case block of code via case i n t number of years entered when open parenthesis years of no claims greater than symbol 10 close parenthesis colon.

Figure 9-23

Case when > 10 executed

  1. 19.

    Press the Enter key to close the console window.

     
  2. 20.

    Start the program again by clicking the Debug menu.

     
  3. 21.

    Choose Start Debugging.

     
  4. 22.

    Type 10 and press the Enter key.

    Figure 9-24 shows the console window and we can see that the second case block of code has been executed.

     

A console window depicts an entry from executing the second case block of code via case i n t number of years entered when open parenthesis years of no claims greater than symbol 8 close parenthesis colon.

Figure 9-24

Case when > 8 executed

  1. 23.

    Press the Enter key to close the console window.

    Repeat the input process for the values 8, 6, 4, and 2.

     

switch with Strings

The C# switch programs we have been writing have switches using an integer. We have therefore executed one block of code, or another, based on the integer value in the case statement. C# also allows us to use the case construct with a string . When we use a string, the construct is the same as we have already coded, but the string must be enclosed in double quotes "".

We will now use a string in the case construct. To do this we will amend the Switch.cs program , so the data read from the console is not converted to an int – we will just keep it as a string. To achieve this, we will also need to change the data type of the variable yearsOfNoClaims from int to string. Rather than changing the existing Switch class, we will create a copy of the class, rename it, and then change the code in the copied class. This is a great technique, as we can reuse existing code and save lots of time having to start a program from “scratch.”
  1. 24.

    Right-click the Switch class.

     
  2. 25.

    Choose Copy.

     
  3. 26.

    Right-click the Chapter9 project.

     
  4. 27.

    Choose Paste.

    The new file Switch – Copy.cs will be added to the project.

     
  5. 28.

    Right-click the Switch – Copy.cs file.

     
  6. 29.

    Choose Rename.

     
  7. 30.

    Type SwitchString.cs as the new name for this class.

     
  8. 31.

    Make sure this new class is open in the editor window, not the original class.

    Looking at the code for the new class in the editor window, we will see an error line under the class name in the code, as shown in Figure 9-25. This is because the class name does not match the name of the file, class, in the Solution Explorer panel and the class name Switch is therefore already in existence in the Chapter9 namespace.

     

An editor window exhibits an error message popping up below the underlined Switch class name in one of the lines of code. The error code is C S 0 101.

Figure 9-25

Class code has not been renamed as shown by the error

Although it says a class called Switch exists, which is correct, we just need to rename the class to match the name we gave it, SwitchString.

We can right-click the word Switch and choose rename, but do not check the boxes that appear and ask about renaming other things as this may also rename the original class. If we did this, we would have two classes with the same name in the same namespace, and we read in Chapter 3 that this is not allowed.
  1. 32.

    Amend the word Switch in the editor window to say SwitchString.cs.

     
  2. 33.

    Amend the code as shown in Listing 9-14 to change the data type of the variable to string instead of int.

     
    static void Main(string[] args)
    {
      /*
      We will setup our variables that will be used in
      the quote application  */
      string yearsOfNoClaims;
Listing 9-14

Change variable type from int to string

  1. 34.

    Amend the code as shown in Listing 9-15 to remove the conversion of the data input by the user, as we want this to remain a string, which is the default for console input.

     
      string yearsOfNoClaims;
      /* Read the user input and convert it to an int */
      Console.WriteLine("How many full years of no claims " +
        "does the driver have? ");
      yearsOfNoClaims = Console.ReadLine();
Listing 9-15

Remove the conversion from string to int

The code line was yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());, and we have removed the conversion from string to Int32.
  1. 35.

    Amend the code as shown in Listing 9-16 to add the new format for the first case block. This will mean enclosing the numbers in double quotes as they are being entered as strings.

     
     switch (yearsOfNoClaims)
     {
       case "11":
       case "12":
       case "13":
       case "14":
       case "15":
Listing 9-16

Case statements accepting string values (double quotes)

  1. 36.

    Amend the code as shown in Listing 9-17 to add the new format for the second and remaining case blocks.

     
     switch (yearsOfNoClaims)
     {
       case "11":
       case "12":
       case "13":
       case "14":
       case "15":
        /*
        This block of code will be executed if the
        yearsofnoclaims is more than 10
        */
        Console.WriteLine("Years of no claims is more" +
          " than 10 but less than 16");
        break;
       case "9":
       case "10":
        /*
        This block of code will be executed if the
        yearsofnoclaims is either 9 or 10
        */
        Console.WriteLine("Years of no claims is either" +
          " 9 or 10");
        break;
       case "7":
       case "8":
        /*
        This block of code will be executed if the
        yearsofnoclaims is either 7 or 8
        */
        Console.WriteLine("Years of no claims is either 7 or 8");
        break;
       case "5":
       case "6":
        /*
        This block of code will be executed if the
        yearsofnoclaims is either 5 or 6
        */
        Console.WriteLine("Years of no claims is either 5 or 6");
        break;
       case "3":
       case "4":
        /*
        This block of code will be executed if the
        yearsofnoclaims is either 3 or 4
        */
        Console.WriteLine("Years of no claims is either 3 or 4");
        break;
       default:
       /*
       This block of code will be executed if the
       yearsofnoclaims is not one of the values in the case
       statements 4 to 15. That means if the value is more than
       15 or less than 4 this block will be executed.
       We need to think, is this what we really want. Certainly
       it does not give us the same result as the if else-if
       */
       Console.WriteLine("Years of no claims is either less " +
         "than 3 or greater than 15");
       break;
      } //End of switch construct    } // End of Main() method
    } // End of SwitchString class
  } // End of Chapter9 namespace
Listing 9-17

All case statements accepting string values (double quotes)

  1. 37.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  2. 38.

    Choose Properties from the pop-up menu.

     
  3. 39.

    Choose the SwitchString class in the Startup object drop-down list, as shown in Figure 9-26.

     

A zoomed Startup object section in the Solution Explorer panel exhibits a highlighted Chapter 9 dot Switch String class from the drop-down list.

Figure 9-26

Set the startup class

  1. 40.

    Click the File menu.

     
  2. 41.

    Choose Save All.

     
  3. 42.

    Click the Debug menu.

     
  4. 43.

    Choose Start Without Debugging.

    The console window will appear and ask the question. Now we can try the values 15, 10, 8, 6, 4, and 2, which will test the six case blocks. We will start with 15.

     
  5. 44.

    Type 15 and press the Enter key.

    Figure 9-27 shows the console window and we can see that the first case block of code that uses the string has been executed.

     

A console window depicts an executed first case block of code via case 15 in quotes colon with the years of no claims is more than 10 but less than 16 entry for 15.

Figure 9-27

Switch case 15

  1. 45.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 46.

    Click the Debug menu.

     
  3. 47.

    Choose Start Without Debugging.

     
  4. 48.

    Type 10 and press the Enter key.

    Figure 9-28 shows the console window and we can see that the second case block of code that uses the string has been executed .

     

A console window depicts an executed second case block of code via case 10 in quotes colon with the years of no claims is either 9 or 10 entry for 10.

Figure 9-28

Switch case 10

  1. 49.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 50.

    Click the Debug menu.

     
  3. 51.

    Choose Start Without Debugging.

     
  4. 52.

    Type 8 and press the Enter key.

    Figure 9-29 shows the console window and we can see that the third case block of code that uses the string has been executed.

     

A console window depicts an executed third case block of code via case 8 in quotes colon with the years of no claims is either 7 or 8 entry for 8.

Figure 9-29

Switch case 8

  1. 53.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 54.

    Click the Debug menu.

     
  3. 55.

    Choose Start Without Debugging.

     
  4. 56.

    Type 6 and press the Enter key.

    Figure 9-30 shows the console window and we can see that the fourth case block of code that uses the string has been executed.

     

A console window depicts an executed fourth case block of code via case 6 in quotes colon with the years of no claims is either 5 or 6 entry for 6.

Figure 9-30

Switch case 6

  1. 57.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 58.

    Click the Debug menu.

     
  3. 59.

    Choose Start Without Debugging.

     
  4. 60.

    Type 4 and press the Enter key.

    Figure 9-31 shows the console window and we can see that the fifth case block of code that uses the string has been executed.

     

A console window depicts an executed fifth case block of code via case 4 in quotes colon with the years of no claims is either 3 or 4 entry for 4.

Figure 9-31

Switch case 4

  1. 61.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 62.

    Click the Debug menu.

     
  3. 63.

    Choose Start Without Debugging.

     
  4. 64.

    Type 2 and press the Enter key.

    Figure 9-32 shows the console window and we can see that the sixth case block, the default block, of code that uses the string has been executed.

     

A console window depicts an executed default block via default colon with the years of no claims is either less than 3 or greater than 15 entry for 2.

Figure 9-32

Switch case default

  1. 65.

    Press the Enter key to close the console window.

     

switch with Strings

Additional Example

We should remember the coding technique for displaying data using placeholders that we applied earlier:
  • The placeholder has the format placeholders {}.

  • Each placeholder has a number contained in the open and close braces.

  • The number represents the position of the variable name, which is in the comma-separated list at the end of the statement.

  • The variables are numbered starting with a 0, then a 1, etc. This means the numbers are zero indexed.

The placeholder format is very neat and means we do not have to keep opening and closing the double quotes to insert the concatenation + symbol. This new example will reinforce selection using the switch statement with string values.
  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class SwitchStringVehicleModel.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Amend the code as shown in Listing 9-18 to add the required variables and make use of the new WriteLine() format within the switch construct.

     
namespace Chapter9
{
  internal class SwitchStringVehicleModel
  {
    static void Main()
    {
      /*
      In this section we declare the two variables of data type
      string that we will use throughout the program code.
      */
      string vehicleModel;
      string vehicleManufacturer;
      Console.WriteLine();
      Console.WriteLine("What is the model of the vehicle? ");
      /*
      In this section we read the user input from the console.
      The console input is by default a string data type which
      means we can directly assign the value to the string
      variable called vehicleModel. */
      vehicleModel = Console.ReadLine();
      /*
      In this section we use the string variable called
      vehicleModel in the case statement to decide which block
      of code will be executed. The blocks of code therefore
      will be based on the model of the vehicle and the code will
      set the value of the variable called vehicleManufacturer.
      */
      switch (vehicleModel)
      {
        case "Edge":
        case "Fiesta":
        case "Focus":
        case "Kuga":
        case "Mondeo":
        case "Mustang":
          vehicleManufacturer = "Ford";
          break;
        case "Astra":
        case "Corsa":
        case "Insignia":
        case "Viva":
          vehicleManufacturer = "Vauxhall";
          break;
        case "Altima":
        case "Juke":
        case "Sentra":
          vehicleManufacturer = "Nissan";
          break;
        case "C-Class":
        case "E-Class":
        case "S-Class":
        case "GLA":
        case "GLC":
        case "GLE":
          vehicleManufacturer = "Mercedes Benz";
          break;
        default:
          vehicleManufacturer = "unknown";
          break;
      }
      /*
      Here we will write the same message to the console in two
      different ways so we can use a new technique
      */
      /*
      In this statement we are writing data to the console in
      our normal way with a concatenated (joined) string and
      this works fine
      */
      Console.WriteLine(" The " + vehicleModel + " " +
        "manufacturer is " + vehicleManufacturer);
      /*
      In this statement we are writing data to the console in a
      different way using a string which has placeholders {}.
      Each place holder has a number and this number represents
      the position of the variable name which is in the comma
      separated list at the end of the statement. The variables
      are numbered starting with a 0 then a 1 etc (zero indexed)
      and are at the end of the statement.
      The example below effectively means
      Console.WriteLine(" The vehicleModel manufacturer is
      vehicleManufacturer ");
      This new format is very neat and means we do not have to
      keep opening and closing the double quotes and having the
      concatenation + symbol.
      */
      Console.WriteLine(" The {0} manufacturer is {1} ",
        vehicleModel, vehicleManufacturer);
    } // End of Main() method
  } // End of SwitchStringVehicleModel class
} // End of Chapter9 namespace
Listing 9-18

Switch using strings and using WriteLine() with placeholders

  1. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  2. 8.

    Choose Properties from the pop-up menu.

     
  3. 9.

    Choose the SwitchStringVehicleModel.cs class in the Startup object drop-down list.

     
  4. 10.

    Click the File menu.

     
  5. 11.

    Choose Save All.

     
  6. 12.

    Click the Debug menu.

     
  7. 13.

    Choose Start Without Debugging.

    The console window will appear and ask the question. Now we can try the string values Mustang, Corsa, Juke, S-Class, and Pacifica, which will test the five case blocks. We will start with Mustang.

     
  8. 14.

    Type Mustang and press the Enter key.

    Figure 9-33 shows the console window and we can see that the first case block of code has been executed, and the different WriteLine() formats have output the same message, but one has used concatenation and the other has used the placeholders.

     

A console window depicts Mustang as the case block 1 colon entry along with two of the Mustang manufacturer Ford entries displayed with concatenation and placeholders, respectively.

Figure 9-33

Switch case block 1

  1. 15.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 16.

    Click the Debug menu.

     
  3. 17.

    Choose Start Without Debugging.

     
  4. 18.

    Type Corsa and press the Enter key.

    Figure 9-34 shows the console window and we can see that the second case block of code has been executed.

     

A console window depicts Corsa as the case block 2 colon entry along with two of the Corsa manufacturer Vauxhall entries displayed with concatenation and placeholders, respectively.

Figure 9-34

Switch case block 2

  1. 19.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 20.

    Click the Debug menu.

     
  3. 21.

    Choose Start Without Debugging.

     
  4. 22.

    Type Juke and press the Enter key.

    Figure 9-35 shows the console window and we can see that the third case block of code has been executed.

     

A console window depicts Juke as the case block 3 colon entry along with two the Juke manufacturer is Nissan entries displayed with concatenation and placeholders, respectively.

Figure 9-35

Switch case block 3

  1. 23.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 24.

    Click the Debug menu.

     
  3. 25.

    Choose Start Without Debugging.

     
  4. 26.

    Type S-Class and press the Enter key.

    Figure 9-36 shows the console window and we can see that the fourth case block of code has been executed.

     

A console window depicts S-Class as the case block 4 colon entry along with two of the S-Class manufacturer Mercedes Benz entries displayed with concatenation and placeholders, respectively.

Figure 9-36

Switch case block 4

  1. 27.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 28.

    Click the Debug menu.

     
  3. 29.

    Choose Start Without Debugging.

     
  4. 30.

    Type Pacifica and press the Enter key.

    Figure 9-37 shows the console window and we can see that the fifth case block, the default case block, of code has been executed.

     

A console window depicts Pacifica as the default colon entry along with two Pacifica manufacturer unknown entries displayed with concatenation and placeholders, respectively.

Figure 9-37

Switch case block 5 – the default case block

  1. 31.

    Press the Enter key to close the console window.

    An issue to be considered when using strings with the case statement is that checking is case sensitive. This should be no surprise to us really, as we will be familiar with writing and will know that these are all different strings:
    • Mustang

    • MUSTANG

    • mustang

    • mUSTANG

     
So, if these are all different in our writing, then we can imagine that the C# compiler will also treat them as being different. This will mean that the user needs to input the data in precisely the same way that we as the developer have checked the string in the switch statement. This is certainly an issue and not a very satisfactory experience for the end user. To avoid such issues, different techniques can be used by us as developers, such as using a method to convert the user input to uppercase and then having the case statements have uppercase text. The uppercase method belongs to the String class and is called ToUpper(), as shown in Figure 9-38.

A window exhibits a highlighted To Upper method from a scrollable list that pops up below an underlined To in the line starting with the Switch class.

Figure 9-38

The ToUpper() method from the String class

We will see more of this in Chapter 15 on string handling, but as a “taster,” this might be coded as shown in Listing 9-19.
      switch (vehicleModel.ToUpper())
      {
        case "EDGE":
        case "FIESTA":
        case "FOCUS":
        case "KUGA":
        case "MONDEO":
        case "MUSTANG":
          vehicleManufacturer = "Ford";
          break;
Listing 9-19

ToUpper() method of the String class

If the user inputs any string, it will be converted to uppercase when the switch statement is executed. So, if the user enters mUsTaNg, the code will convert it to uppercase MUSTANG and the case statement will find the correct manufacturer. We could also use the ToUpper() method on the output, as shown in Listing 9-20, and the output would show uppercase letters as shown in Figure 9-39.
      Console.WriteLine(" The {0} manufacturer is {1} ",
        vehicleModel.ToUpper(), vehicleManufacturer);
Listing 9-20

ToUpper() method of the String class

A console window exhibits an uppercase Mustang entry in the second entry of the write line due to the upper close and open parentheses method.

Figure 9-39

The ToUpper() method from the String class

For now, do not worry about this uppercase and lowercase.

Logical Operators

We said earlier

We will also look at the logical operators AND (&&), || (OR), and ! (NOT).

Well, now is the time to use them, by building on the if construct we have learned.

AND

Looking at the AND operator , we will see that both parts must be TRUE for the whole statement to be TRUE. Listing 9-21 shows the AND in an if construct, even though in C# coding we will not use the word AND.
    if (yearsOfNoClaims > 10 AND policyHolderAge > 50)
    {
      // Some business logic
    }
Listing 9-21

Simplified version of an AND operator

Looking at Table 9-2, we can see all the possibilities for an AND operator when there are two parts.
Table 9-2

The AND, &&, operator

First part

Operator

Second part

Result

TRUE

AND

TRUE

= TRUE

TRUE

AND

FALSE

= FALSE

FALSE

AND

TRUE

= FALSE

FALSE

AND

FALSE

= FALSE

OR

Looking at the OR operator, we will see that only one part must be TRUE for the whole statement to be TRUE. Listing 9-22 shows the OR in an if construct, even though in C# coding we will not use the word OR.
    if (yearsOfNoClaims > 10 OR policyHolderAge > 50)
    {
      // Some business logic
    }
Listing 9-22

Simplified version of an OR operator

Looking at Table 9-3, we can see all the possibilities for an OR operator.
Table 9-3

The OR, !!, operator

First part

Operator

Second part

Result

TRUE

OR

TRUE

= TRUE

TRUE

OR

FALSE

= TRUE

FALSE

OR

TRUE

= TRUE

FALSE

OR

FALSE

= FALSE

NOT

Looking at the NOT operator , we will see that the current value becomes the opposite of what it is: TRUE becomes FALSE and FALSE becomes TRUE. An example of using NOT in the if construct is shown in Listing 9-23.
    if (!yearsOfNoClaims > 10)
    {
      // Some business logic
    }
Listing 9-23

Simplified version of a NOT, !, operator

Looking at Table 9-4, we can see all the possibilities for a NOT operator.
Table 9-4

The NOT, !, operator

Operator

First part

Result

NOT

TRUE

= FALSE

NOT

FALSE

= TRUE

In C# the logical operators will only evaluate the second part of the expression if it is necessary. “Why?” we might ask. Well, we will see from the following examples that it makes sense to use this short-circuit evaluation to save needless evaluation.

AND

In our truth table , Table 9-2, we saw that the only combination that evaluates to TRUE is when both parts of the expression are TRUE. So we can short-circuit any combinations that start with a FALSE:

if(6>7 AND 9<10) equates to if(FALSE AND TRUE), which equates to FALSE.

As the first part evaluates to FALSE there is no point in evaluating the second part.

OR

In our truth table, Table 9-3, we saw that a TRUE or a FALSE as the first part could lead to an overall evaluation of TRUE. So we cannot short-circuit when using the OR construct.

Let's code some C# and build our programming muscle.

Using the AND Operator

  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class SelectionAnd.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Amend the code to add the Main() method as in Listing 9-24.

     
namespace Chapter9
{
  internal class SelectionAnd
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of SelectionAnd class
} // End of Chapter9 namespace
Listing 9-24

Adding the Main() method

Now we need to set this class as the startup class.
  1. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  2. 8.

    Choose Properties from the pop-up menu.

     
  3. 9.

    Choose the SelectionAnd.cs class in the Startup object drop-down list.

     
  4. 10.

    Close the Properties window.

     
  5. 11.

    Amend the code to add the variables required, as in Listing 9-25.

     
    static void Main(string[] args)
    {
      /*
      We will setup our variables that will be used in
      the quote application
      */
      int yearsOfNoClaims;
      int ageOfDriver;
    } // End of Main() method
Listing 9-25

Adding the variables

  1. 12.

    Amend the code, as in Listing 9-26, to request user input for the years of no claims and convert it to an int.

     
      int yearsOfNoClaims;
      int ageOfDriver;
      /* Read the user input and convert it to an int */
      Console.WriteLine("How many full years of no claims does the driver have? ");
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
    } // End of Main() method
Listing 9-26

Accept user input and convert to an int

  1. 13.

    Amend the code, as in Listing 9-27, to request user input for the driver age and convert it to an int.

     
      yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("What is the current age of the driver? ");
      ageOfDriver = Convert.ToInt32(Console.ReadLine());
    } // End of Main() method
Listing 9-27

Accept user input and convert to an int

Now we will check if the number of years of no claims is greater than 10 and if the age of the driver is greater than 40:

  • If these are both true, we execute code in the if block.

  • Otherwise, move to the else block and execute the code in this block.

  1. 14.

    Amend the code, as in Listing 9-28.

     
      ageOfDriver = Convert.ToInt32(Console.ReadLine());
      /*
      Now we will check if the years of no claims is greater
      than 10 AND if the age of the driver is greater than 40.
      If both are TRUE we have the Boolean expression
      TRUE AND TRUE which equates to TRUE and we then we
      execute some lines of code which exist between the
      curly braces of the code block, otherwise the program
      moves to the else code block and execute some lines of
      code in this code block
      */
      if (yearsOfNoClaims > 10 && ageOfDriver > 40)
      {
      /*
        This block of code will be executed if both
        parts of the condition are TRUE
      */
        Console.WriteLine("This quote is eligible for a 10% discount");
      } // End of true part
      else
      {
      /*
      This block of code will be executed if the one
      part of the condition is FALSE
      */
        Console.WriteLine("This quote is ineligible for a discount");
      } // End of false part
    } // End of Main() method
  } // End of SelectionAnd class
} // End of Chapter9 namespace
Listing 9-28

Use selection through an if-else statement

Testing TRUE AND TRUE
  1. 15.

    Click the File menu.

     
  2. 16.

    Choose Save All.

     
  3. 17.

    Click the Debug menu.

     
  4. 18.

    Choose Start Without Debugging.

     
  5. 19.

    Click in the console window.

     
  6. 20.

    Type 20 as the number of years of no claims.

     
  7. 21.

    Press the Enter key on the keyboard.

     
  8. 22.

    Type 50 as the current age of the driver.

     
  9. 23.

    Press the Enter key on the keyboard.

    Figure 9-40 shows the console window with the message that a discount is applicable, as 20 is greater than 10 AND 50 is greater than 40.

     

A console window depicts the text, This quote is eligible for a 10 percent discount entry via the execution of a true block for 20 years of no claims and driver's age at 50.

Figure 9-40

True section of if-else executed

  1. 24.

    Press the Enter key to close the console window.

    Testing FALSE AND TRUE

     
  2. 25.

    Click the File menu.

     
  3. 26.

    Choose Save All.

     
  4. 27.

    Click the Debug menu.

     
  5. 28.

    Choose Start Without Debugging.

     
  6. 29.

    Click in the console window.

     
  7. 30.

    Type 10 as the number of years of no claims.

     
  8. 31.

    Press the Enter key on the keyboard.

     
  9. 32.

    Type 50 as the current age of the driver.

     
  10. 33.

    Press the Enter key on the keyboard.

    Figure 9-41 shows the console window with the message that no discount is applicable, as 50 is greater than 40 BUT 10 is not greater than 10.

     

A console window depicts the text, This quote is ineligible for a discount entry via the execution of a false block for 10 years of no claims and driver's age at 50.

Figure 9-41

False section of if-else executed

  1. 34.

    Press the Enter key to close the console window.

    Testing TRUE AND FALSE

     
  2. 35.

    Click the File menu.

     
  3. 36.

    Choose Save All.

     
  4. 37.

    Click the Debug menu.

     
  5. 38.

    Choose Start Without Debugging.

     
  6. 39.

    Click in the console window.

     
  7. 40.

    Type 20 as the number of years of no claims.

     
  8. 41.

    Press the Enter key on the keyboard.

     
  9. 42.

    Type 30 as the current age of the driver.

     
  10. 43.

    Press the Enter key on the keyboard.

    Figure 9-42 shows the console window with the message that no discount is applicable as 20 is greater than 10 BUT 30 is not greater than 40.

     

A console window depicts the text, This quote is ineligible for a discount entry via the execution of a false block for 20 years of no claims and driver's age at 30.

Figure 9-42

False section of if-else executed

  1. 44.

    Press the Enter key to close the console window.

     

Let's code some C# and build our programming muscle.

Using the OR Operator

  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class SelectionOR.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Create a Main() method within the class, as this was not produced automatically. Type svm and press Tab twice, and then delete the unwanted imports.

    Now we need to set this class as the startup class .

     
  7. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  8. 8.

    Choose Properties from the pop-up menu.

     
  9. 9.

    Choose the SelectionOR class in the Startup object drop-down list.

     
  10. 10.

    Close the Properties window.

     
  11. 11.

    Open the SelectionAnd file and copy the code from within the Main() method.

     
  12. 12.

    Move back to the SelectionOR file in the editor and paste the copied code between the open and close curly braces, { }, of the Main() method.

    We will amend the code to use the logical operator OR rather than the logical operator AND. Within the copied code, we will change the && to || and change the comments to match. This means our code will
    • Check if the number of years of no claims is greater than 10 OR if the age of the driver is greater than 40:

      If these are both true, we execute code in the if block.

      If one of these is true, we execute code in the if block.

      Otherwise, move to the else block and execute the code in this block.

     
  13. 13.

    Amend the code , as in Listing 9-29.

     
      ageOfDriver = Convert.ToInt32(Console.ReadLine());
      /*
      Now we will check if the years of no claims is greater
      than 10 OR if the age of the driver is greater than 40.
      If both are TRUE we have the Boolean expression
      TRUE AND TRUE which equates to TRUE or if one of them
      is TRUE we have the Boolean expression TRUE OR FALSE
      or FALSE OR TRUE which equates to TRUE and we then we
      execute some lines of code which exist between the curly
      braces of the code block, otherwise the program moves
      to the else code block and executes some lines of code
      in this code block
      */
      if (yearsOfNoClaims > 10 || ageOfDriver > 40)
      {
        /*
          This block of code will be executed if one
          part of the condition are TRUE
        */
        Console.WriteLine("This quote is eligible for a 10% discount");
      } // End of true part
      else
      {
        /*
        This block of code will be executed if the one
        part of the condition is FALSE
        */
        Console.WriteLine("This quote is ineligible for a discount");
      } // End of false part
Listing 9-29

Use the OR ( || ) instead of the AND ( && )

Testing TRUE OR TRUE
  1. 14.

    Click the File menu.

     
  2. 15.

    Choose Save All.

     
  3. 16.

    Click the Debug menu.

     
  4. 17.

    Choose Start Without Debugging.

     
  5. 18.

    Click in the console window.

     
  6. 19.

    Type 20 as the number of years of no claims.

     
  7. 20.

    Press the Enter key on the keyboard.

     
  8. 21.

    Type 50 as the current age of the driver.

     
  9. 22.

    Press the Enter key on the keyboard.

    Figure 9-43 shows the console window with the message that a discount is applicable as 20 is greater than 10 OR 50 is greater than 40. In this case both are TRUE, which equates to TRUE.

     

A console window depicts the execution of a true block with the text, This quote is eligible for a 10 percent discount entry for 20 years of no claims and driver's age at 50.

Figure 9-43

True section of if-else executed

  1. 23.

    Press the Enter key to close the console window.

    Testing FALSE OR TRUE

     
  2. 24.

    Click the File menu.

     
  3. 25.

    Choose Save All.

     
  4. 26.

    Click the Debug menu.

     
  5. 27.

    Choose Start Without Debugging.

     
  6. 28.

    Click in the console window.

     
  7. 29.

    Type 10 as the number of years of no claims.

     
  8. 30.

    Press the Enter key on the keyboard.

     
  9. 31.

    Type 50 as the current age of the driver.

     
  10. 32.

    Press the Enter key on the keyboard.

    Figure 9-44 shows the console window with the message that a discount is applicable as 10 is not greater than 10 (FALSE) OR 50 is greater than 40 (TRUE). In this case we have FALSE OR TRUE, which equates to TRUE.

     

A console window depicts the text, This quote is eligible for a 10 percent discount entry via the execution of a true block for 20 years of no claims and driver's age at 50.

Figure 9-44

True section of if-else executed

  1. 33.

    Press the Enter key to close the console window.

    Testing TRUE OR FALSE

     
  2. 34.

    Click the File menu.

     
  3. 35.

    Choose Save All.

     
  4. 36.

    Click the Debug menu.

     
  5. 37.

    Choose Start Without Debugging.

     
  6. 38.

    Click in the console window.

     
  7. 39.

    Type 20 as the number of years of no claims.

     
  8. 40.

    Press the Enter key on the keyboard.

     
  9. 41.

    Type 30 as the current age of the driver.

     
  10. 42.

    Press the Enter key on the keyboard.

    Figure 9-45 shows the console window with the message that a discount is applicable as 20 is greater than 10 (TRUE) OR 30 is not greater than 40 (FALSE). In this case we have TRUE OR FALSE, which equates to TRUE.

     

A console window depicts the text, This quote is eligible for a 10 percent discount entry via the execution of a true block for 20 years of no claims and driver's age at 30.

Figure 9-45

True section of if-else executed

  1. 43.

    Press the Enter key to close the console window.

    Testing FALSE OR FALSE

     
  2. 44.

    Click the File menu.

     
  3. 45.

    Choose Save All.

     
  4. 46.

    Click the Debug menu.

     
  5. 47.

    Choose Start Without Debugging.

     
  6. 48.

    Click in the console window.

     
  7. 49.

    Type 10 as the number of years of no claims.

     
  8. 50.

    Press the Enter key on the keyboard.

     
  9. 51.

    Type 30 as the current age of the driver.

     
  10. 52.

    Press the Enter key on the keyboard.

    Figure 9-46 shows the console window with the message that a discount is not applicable as 10 is not greater than 10 (FALSE) OR 30 is not greater than 40 (FALSE). In this case we have FALSE OR FALSE, which equates as FALSE.

     

A console window depicts the text, This quote is ineligible for a discount entry via the execution of a false block for 10 years of no claims and driver's age at 30.

Figure 9-46

False section of if-else executed

  1. 53.

    Press the Enter key.

     

Let's code some C# and build our programming muscle.

Using the NOT Operator

  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class SelectionNOT.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Create a Main() method within the class, as this was not produced automatically, and delete the unwanted imports.

    Remember the shortcut to create the Main() method is to type svm and then press the Tab key twice. Now we need to set this class as the startup class.

     
  7. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  8. 8.

    Choose Properties from the pop-up menu.

     
  9. 9.

    Choose the SelectionNOT class in the Startup object drop-down list.

     
  10. 10.

    Close the Properties window.

     
  11. 11.

    Open the SelectionOR file and copy the code within the Main() method.

     
  12. 12.

    In the Main() method of the SelectionNOT file, paste the copied code.

    Now we will amend the code to use the logical operator NOT. We will
    • Change the || to && (change the OR to an AND).

    • Add brackets around the expression.

    • Add the !, NOT, in front of the brackets.

    • Leave the comments the same.

    The if (!(yearsOfNoClaims > 10 && ageOfDriver > 40)) code line means we are checking if the number of years of no claims is greater than 10 AND if the age of the driver is greater than 40:
    • If these are both true, the expression in the brackets equates to true but we negate it (!) to false, and we do not execute the code in the if block.

    • If one of these is false, the expression in the brackets equates to false but we negate it (!) to true, and we execute the code in the if block.

    • If these are both false, the expression in the brackets equates to false but we negate it (!) to true, and we execute the code in the if block.

    We will now change to an AND expression, add an extra set of brackets () around it, and put a !, NOT, before the new brackets. We will leave the comments as they are.

     
  13. 13.

    Amend the code, as in Listing 9-30.

     
      if (!(yearsOfNoClaims > 10 && ageOfDriver > 40))
      {
        /*
          This block of code will be executed if one
          parts of the condition are TRUE
        */
        Console.WriteLine("This quote is eligible for a 10% discount");
      } // End of true part
Listing 9-30

Use the NOT ( ! ) operator

Testing TRUE AND TRUE
  1. 14.

    Click the File menu.

     
  2. 15.

    Choose Save All.

     
  3. 16.

    Click the Debug menu.

     
  4. 17.

    Choose Start Without Debugging.

     
  5. 18.

    Click in the console window.

     
  6. 19.

    Type 20 as the number of years of no claims.

     
  7. 20.

    Press the Enter key on the keyboard.

     
  8. 21.

    Type 50 as the current age of the driver.

     
  9. 22.

    Press the Enter key on the keyboard.

    Figure 9-47 shows the console window with the message that a discount is not applicable as we have an overall TRUE negated to a FALSE (20 is greater than 10 AND 50 is greater than 40, which means TRUE negated to FALSE, so no discount is applicable).

     

A console window depicts the text, This quote is ineligible for a discount entry via the execution of a false block for 20 years of no claims and driver's age at 50.

Figure 9-47

False section of if-else executed

  1. 23.

    Press the Enter key.

    Testing FALSE AND TRUE

    Start the program again.

     
  2. 24.

    Click the Debug menu.

     
  3. 25.

    Choose Start Without Debugging.

     
  4. 26.

    Click in the console window.

     
  5. 27.

    Type 10 as the number of years of no claims.

     
  6. 28.

    Press the Enter key on the keyboard.

     
  7. 29.

    Type 50 as the current age of the driver.

     
  8. 30.

    Press the Enter key on the keyboard.

    Figure 9-48 shows the console window with the message that a discount is applicable as we have an overall FALSE negated to a TRUE (10 is not greater than 10 AND 50 is greater than 40, which means FALSE negated to TRUE, so a discount is applicable).

     

A console window depicts the execution of a true block with the text, This quote is eligible for a 10 percent discount entry for 10 years of no claims and driver's age at 50.

Figure 9-48

False section of if-else executed

  1. 31.

    Press the Enter key to close the console window.

    Testing TRUE AND FALSE

    Start the program again.

     
  2. 32.

    Click the Debug menu.

     
  3. 33.

    Choose Start Without Debugging.

     
  4. 34.

    Click in the console window.

     
  5. 35.

    Type 20 as the number of years of no claims.

     
  6. 36.

    Press the Enter key on the keyboard.

     
  7. 37.

    Type 30 as the current age of the driver.

     
  8. 38.

    Press the Enter key on the keyboard.

    Figure 9-49 shows the console window with the message that a discount is applicable as we have an overall FALSE negated to a TRUE (20 is greater than 10 AND 30 is not greater than 40, which means FALSE negated to TRUE, so a discount is applicable).

     

A console window depicts the execution of a true block with the text, This quote is eligible for a 10 percent discount entry for 20 years of no claims and driver's age at 30.

Figure 9-49

False section of if-else executed

  1. 39.

    Press the Enter key to close the console window.

     

Conditional Operator (Ternary Operator)

Earlier, we used the if-else construct where there is one block of code executed if the condition is true and another block executed if the condition is false. The code we used is shown in Listing 9-31, with the comments removed.
  if (yearsOfNoClaims > 10)
  {
    Console.WriteLine("Years of no claims is more than 10");
  }// End of true block of code in the if construct
  else
  {
    Console.WriteLine("Years of no claims is less than or " +
      "equal to 10");
  } // End of false block of code in the if construct
Listing 9-31

if-else construct

However, there is another way to do the if-else construct, using the C# conditional operator, or ternary operator as it is also known. The ternary conditional operator will evaluate the Boolean expression and return either true or false. The syntax for the ternary conditional operator is

Condition ? First Expression : Second Expression

So analyzing this syntax, we will see that
  • Condition is a “statement” that must evaluate to true or false.

  • If the condition is true, the First Expression gets executed.

  • If the condition is false, the Second Expression gets executed.

Looking at our if-else example, we could say

Condition is yearsOfNoClaims > 10

First Expression is Console.WriteLine("Years of no claims is more than 10");

Second Expression is Console.WriteLine("Years of no claims is less than or equal to 10");

If we follow this syntax, then our code could be written as
 yearsOfNoClaims > 10 ? "Years of no claims is more than 10" :
                "Years of no claims is less than or equal to 10";

But let's see how we actually write it.

Let's code some C# and build our programming muscle .
  1. 1.

    Right-click the Chapter9 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class Ternary.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Create a Main() method within the class, as this was not produced automatically, and delete the unwanted imports.

    Remember the shortcut to create the Main() method is to type svm and then press the Tab key twice. Now we need to set this class as the startup class.

     
  7. 7.

    Right-click the Chapter9 project in the Solution Explorer panel.

     
  8. 8.

    Choose Properties from the pop-up menu.

     
  9. 9.

    Choose the Ternary class in the Startup object drop-down list.

     
  10. 10.

    Close the Properties window.

    Now we will amend the code to use the ternary conditional operator.

     
  11. 11.

    Amend the code as in Listing 9-32.

     
namespace Chapter9
{
  internal class Ternary
  {
    static void Main(string[] args)
    {
    /*
    We will setup our variables that will be used in
    the quote application
    */
    int yearsOfNoClaims;
    /* Read the user input and convert it to an int */
    Console.WriteLine("How many full years of no claims" +
      " does the driver have? ");
    yearsOfNoClaims = Convert.ToInt32(Console.ReadLine());
    // Assign the result of the ternary to a string variable
    string message = yearsOfNoClaims > 10 ?
              "Years of no claims is more than 10" :
              "Years of no claims is less than or equal to 10";
    // Display the result of the ternary condition
    Console.WriteLine(message);
    } // End of Main() method
  } // End of Ternary class
} // End of Chapter9 namespace
Listing 9-32

Ternary operator

  1. 12.

    Click the File menu.

     
  2. 13.

    Choose Save All.

     
  3. 14.

    Click the Debug menu.

     
  4. 15.

    Choose Start Without Debugging.

     
  5. 16.

    Click in the console window.

     
  6. 17.

    Type 5 as the number of years of no claims.

     
  7. 18.

    Press the Enter key on the keyboard.

    Figure 9-50 shows the console window with the message for the FALSE block as 5 is not greater than 10.

     

A console window depicts the execution of the false block of a ternary with the years of no claims being less than or equal to 10 entry for 5.

Figure 9-50

False section of ternary executed

  1. 19.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 20.

    Click the Debug menu.

     
  3. 21.

    Choose Start Without Debugging.

     
  4. 22.

    Click in the console window.

     
  5. 23.

    Type 15 as the number of years of no claims.

     
  6. 24.

    Press the Enter key on the keyboard.

    Figure 9-51 shows the console window with the message for the TRUE block as 15 is greater than 10.

     

A console window depicts the execution of the true block of a ternary with the years of no claims is more than 10 entry for 15.

Figure 9-51

True section of ternary executed

  1. 25.

    Press the Enter key to close the console window.

     

Code Analysis

We said earlier

If we follow this syntax, then our code could be written as

yearsOfNoClaims > 10 ? "Years of no claims is more than 10" : "Years of no claims is less than or equal to 10";

But we have written the code using an assignment as in Listing 9-33.
    // Assign the result of the ternary to a string variable
    string message = yearsOfNoClaims > 10 ?
              "Years of no claims is more than 10" :
              "Years of no claims is less than or equal to 10";
Listing 9-33

Ternary operator

Not putting the assignment causes the error message as shown in Figure 9-52.

A window exhibits an error message popping up below the underlined line of code that reads years of no claims greater than the symbol 10 question mark. The error code is C S 0 201.

Figure 9-52

Ternary error message when not assigned

So our quote was slightly inaccurate as we need to assign the ternary to a value.

Nested Ternary Conditional Operator

We saw that the ternary conditional operator syntax was

Condition ? First Expression : Second Expression

We can incorporate another ternary conditional operator as the second expression, and in this second ternary conditional operator, we can add another ternary conditional operator as the second expression in it. We can continue the nesting as required. Warning: This can get complex to read and understand, as we are essentially doing an if-elseif-elseif and so on.

We will now amend the code, as in Listing 9-34, to do the same thing as our if else if example but using the ternary operator.
  1. 26.

    Amend the code as in Listing 9-34.

     
    // Assign the result of the ternary to a string variable
    string message = yearsOfNoClaims > 10 ?
              "Years of no claims is more than 10" :
              "Years of no claims is less than or equal to 10";
    // Display the result of the ternary condition
    Console.WriteLine(message);
    // Assign the result of the ternary to a string variable
    string newMessage = yearsOfNoClaims > 10 ?
            "Years of no claims is more than 10" :
            yearsOfNoClaims > 8 ?
            "Years of no claims is either 9 or 10" :
            yearsOfNoClaims > 6 ?
            "Years of no claims is either 7 or 8" :
            yearsOfNoClaims > 4 ?
            "Years of no claims is either 5 or 6" :
            yearsOfNoClaims > 2 ?
            "Years of no claims is either 3 or 4" :
            "Years of no claims is 2, 1, 0 " +
            "or indeed a negative number of years " +
            "because of a penalty being enforced on our policy";
      // Display the result of the new ternary condition
      Console.WriteLine(newMessage);
    } // End of Main() method
  } // End of Ternary class
} // End of Chapter9 namespace
Listing 9-34

Ternary operator

Before we run the code, let us look at the nested ternary conditional operator in a more readable form:

yearsOfNoClaims > 10 ? "Years of no claims is more than 10" :

yearsOfNoClaims > 8 ? "Years of no claims is either 9 or 10" :

yearsOfNoClaims > 6 ? "Years of no claims is either 7 or 8" :

yearsOfNoClaims > 4 ? "Years of no claims is either 5 or 6" :

yearsOfNoClaims > 2 ? "Years of no claims is either 3 or 4": "Years of no claims is 2, 1, 0 or indeed a negative number of years because of a penalty being enforced on our policy";

  • The second expression of the first ternary is ternary starting with yearsOfNoClaims > 8.

  • The second expression of the second ternary is ternary starting with yearsOfNoClaims > 6.

  • The second expression of the third ternary is ternary starting with yearsOfNoClaims > 4.

  • The second expression of the fourth ternary is ternary starting with yearsOfNoClaims > 2.

  1. 27.

    Click the File menu.

     
  2. 28.

    Choose Save All.

     
  3. 29.

    Click the Debug menu.

    The console window will appear and ask the question. Now we can try the values 10, 8, 6, 4, and 2, which will test the five ternary sections. We will start with 10.

     
  4. 30.

    Type 10 as the number of years of no claims.

     
  5. 31.

    Press the Enter key on the keyboard.

    Figure 9-53 shows the console window, and we can see that the false part of the first ternary section has executed and there is another ternary and the true section of this ternary has been executed:

    yearsOfNoClaims > 8 ? "Years of no claims is either 9 or 10"

     

A console window depicts the execution of the first part of the nested ternary true section with the years of no claims is either 9 or 10 entry for 10.

Figure 9-53

Nested ternary – first part executed

  1. 32.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 33.

    Click the Debug menu.

     
  3. 34.

    Choose Start Without Debugging.

     
  4. 35.

    Type 8 and press the Enter key.

    The console window will appear, as shown in Figure 9-54, and we can see that the false part of the first ternary section has executed, there is another ternary and the false section of this ternary has been executed, and there is another ternary and the true section of this has been executed:

    yearsOfNoClaims > 6 ? "Years of no claims is either 7 or 8"

     

A console window depicts the execution of the first part of the nested ternary true section with the years of no claims as either 9 or 10 entry for 10.

Figure 9-54

Nested ternary – second part executed

  1. 36.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 37.

    Click the Debug menu.

     
  3. 38.

    Choose Start Without Debugging.

     
  4. 39.

    Type 6 and press the Enter key.

    The console window will appear, as shown in Figure 9-55, and we can see that the false part of the first ternary section has executed, there is another ternary and the false section of this ternary has been executed, there is another ternary and the false section of this has been executed, and there is another ternary and the true section of this ternary has been executed:

    yearsOfNoClaims > 4 ? "Years of no claims is either 5 or 6" :

     

A console window depicts the execution of the third part of the nested ternary true section with the years of no claims as either 5 or 6 entry for 6.

Figure 9-55

Nested ternary – third part executed

  1. 40.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 41.

    Click the Debug menu.

     
  3. 42.

    Choose Start Without Debugging.

     
  4. 43.

    Type 4 and press the Enter key.

    The console window will appear, as shown in Figure 9-56, and we can see that the false part of the first ternary section has executed, there is another ternary and the false section of this ternary has been executed, there is another ternary and the false section of this has been executed, there is another ternary and the false section of this ternary has been executed, and there is another ternary and the true section of this ternary has been executed:

    yearsOfNoClaims > 2 ? "Years of no claims is either 3 or 4":

     

A console window depicts the execution of the fourth part of the nested ternary true section with the years of no claims as either 3 or 4 entry for 4.

Figure 9-56

Nested ternary – fourth part executed

  1. 44.

    Press the Enter key to close the console window.

    Start the program again.

     
  2. 45.

    Click the Debug menu.

     
  3. 46.

    Choose Start Without Debugging.

     
  4. 47.

    Type 2 and press the Enter key.

    The console window will appear as shown in Figure 9-57 and we can see that the final ternary false section has been executed.

     

A console window depicts the execution of the fifth part of the nested ternary true section with an entry that starts with years of no claims as either 2, 1, 0 for 2.

Figure 9-57

Nested ternary – fifth part executed

  1. 48.

    Press the Enter key to close the console window.

    Whoa, whoa, let us catch our breath after that nested ternary code block. The code works and gives us the same results as the if else if code block. However, are we thinking that this ternary code looks confusing compared with the if else if code block? Remember we talked about clean code, so if we see this as confusing and not as readable as the if else if code block, we should not use it. We have choice in how we write our code, but we have a responsibility to make the code readable and easy to maintain.

     

Chapter Summary

In this chapter we have learned about a very important programming concept called selection and have seen that
  • Selection in C# can have different formats, including

    The if construct

    The if-else construct

    The if else if construct

    The switch construct and the case label

    Ternary conditional operator

  • The case construct can use numeric or string data types.

  • The case label is case sensitive.

  • the ternary conditional operator can replace the if else construct

  • There is a different way to display data to the console with the use of “placeholders” {}.

  • C# has a string handling class with useful methods, one of which is the ToUpper() method.

  • We can have more than one class in a package.

We are making great progress in our programming of C# applications and we should be proud of our achievements. In finishing this chapter and increasing our knowledge, we are advancing to our target.

An illustration of concentric circles with two differently colored regions above a text that reads, Our target is getting closer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.220.21