© 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_25

25. Programming Labs

Gerard Byrne1  
(1)
Belfast, Ireland
 

C# Practice Exercises

The lab exercises that follow will give us an opportunity to practice what we have learned. We should complete the labs by referring to the book chapters when we are unsure about how to do something, but more importantly we should look at the previous code we have written. The code we have written should be an invaluable source of working code, and it is important not to “reinvent the wheel.” Use the code - copy, paste, and amend it if required. Reuse the code – that is what the professional developer would do and is expected to do. Professional software developers are expected to create applications as fast and accurately as possible, and reusing existing code is one technique they apply, so why should we be any different?

If we really get stuck, there are sample solutions following the labs and we can refer to these, but it is important we understand any code that we copy and paste. It is also important we enjoy the challenge of developing solutions for each lab. We will apply the learning from the chapters, but more importantly we will develop our own techniques and style for coding , debugging , and problem solving.

Think about the saying

Life begins at the edge of our comfort zone.

We will inevitably feel at the edge of our programming ability, but every new thing we learn in completing each lab should make us feel better and encourage us to learn more. While we may be “frightened” and “uncomfortable” completing the coding labs, the process will lead us to grow and develop our coding skills and build our programming muscle. We might find it “painful” at times but that is the reality of programming. We will find it exciting and challenging as we are stretched and brought to a place we have not been to before.

Chapter 4 Labs: WriteLine( )

Lab 1

Write a C# console application, using the WriteLine() command, that will display the letter E using *’s to form the shape, for example, one line could be Console.WriteLine(“*******”);.

Lab 2

Write a C# console application, using the WriteLine() command, that will display the letter A using *’s to form the shape, for example, one line could be Console.WriteLine (“ *”);.

Lab 3

Write a C# console application that will display your name and address in a format that might look like a label for an envelope – name on the first line, address line 1 on the second line, etc.

Lab 4

Using the same code that you developed for Lab 3, the name and address label, add a statement between each of the name and address lines that will require the user to press Enter on the keyboard before the display moves to the next line .

Lab 1: Possible Solution with output shown in Figure 25-1

namespace Labs.Chapter04
{
  internal class Lab1
  {
    static void Main(string[] args)
    {
      Console.WriteLine("*******");
      Console.WriteLine("*");
      Console.WriteLine("*");
      Console.WriteLine("*******");
      Console.WriteLine("*");
      Console.WriteLine("*");
      Console.WriteLine("*******");
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter04 namespace

A window has a series of asterisks formed in the shape of an upper case letter E.

Figure 25-1

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-2

namespace Labs.Chapter04
{
  internal class Lab2
  {
    static void Main(string[] args)
    {
      Console.WriteLine("      *");
      Console.WriteLine("     * *");
      Console.WriteLine("    *   *");
      Console.WriteLine("   *******");
      Console.WriteLine("  *       *");
      Console.WriteLine(" *         *");
      Console.WriteLine("*           *");
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter04 namespace

A window has a series of asterisks formed in the shape of an upper case letter A.

Figure 25-2

Lab 2 output

Lab 3: Possible Solution with output shown in Figure 25-3

namespace Labs.Chapter04
{
  internal class Lab3
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Mer Gerard Byrne");
      Console.WriteLine("1 Any Street");
      Console.WriteLine("Any Road");
      Console.WriteLine("Belfast");
      Console.WriteLine("BT1 1AN");
    } // End of Main() method
  } // End of Lab3 class
} //End of Labs.Chapter04 namespace

A window contains 5 lines that read as follows, Mister Gerard Byrne, 1 any street, any road, Belfast, B T 1 1 A N, respectively.

Figure 25-3

Lab 3 output

Lab 4: Possible Solution with output shown in Figure 25-4

namespace Labs.Chapter04
{
  internal class Lab4
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Mr Gerard Byrne");
      Console.WriteLine("Press the enter key to continue");
      Console.ReadLine();
      Console.WriteLine("1 Any Street");
      Console.WriteLine("Press the enter key to continue");
      Console.ReadLine();
      Console.WriteLine("Any Road");
      Console.WriteLine("Press the enter key to continue");
      Console.ReadLine();
      Console.WriteLine("Belfast");
      Console.WriteLine("Press the enter key to continue");
      Console.ReadLine();
      Console.WriteLine("BT1 1AN");
    } // End of Main() method
  } // End of Lab4 class
} //End of Labs.Chapter04 namespace

A window has the texts, Mister Gerard Byrne, 1 any street, any road, Belfast, and B T 1 1 A N. Between each is the line, press any key to continue.

Figure 25-4

Lab 4 output

Chapter 6 Labs: Data Types

Lab 1

Write a C# console application that will calculate and display the area of a rectangle using a length of 20 and a breadth of 10, which should be hard-coded in the code. The formula for the area of a rectangle is length multiplied by breadth.

Lab 2

Write a C# console application that will calculate and display the area of a rectangle using the length and breadth that are input at the console by the user. The formula for the area of a rectangle is length multiplied by breadth.

Lab 3

Using the code from Lab 2, write a C# console application that will calculate and display the volume of a cuboid using the length, breadth, and height that are input at the console by the user. The formula for the volume of a cuboid is length multiplied by breadth multiplied by height.

Lab 4

Write a C# console application that will accept user input regarding the credit card details required for making an online purchase . The details required are
  • Credit card number – Contains 16 digits and hyphens between each 4 digits

  • Card expiry month – A number from 1 to 12 (Jan to Dec)

  • Card expiry year – A two-digit number for the year, for example, 23

  • Card issue number – A single-digit number

  • Three-digit security code – A three-digit number

  • Card holder name on card – A string

Display to the console the details read from the user.

Lab 1: Possible Solution with output shown in Figure 25-5

namespace Labs.Chapter06
{
  internal class Lab1
  {
    static void Main(string[] args)
    {
      int length;
      int breadth;
      int area;
      length = 20;
      breadth = 10;
      area = length * breadth;
      Console.WriteLine();
      Console.WriteLine($"The area of the rectangle is {area}
      square centimetres");
      Console.WriteLine();
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter06 namespace

A window contains a text that reads as follows, The area of the rectangle is 200 square meters.

Figure 25-5

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-6

namespace Labs.Chapter06
{
  internal class Lab2
  {
    static void Main(string[] args)
    {
      int length;
      int breadth;
      int area;
      Console.WriteLine("What is the length of the rectangle in
      centimetres");
      length = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("What is the breadth of the rectangle in
      centimetres");
      breadth = Convert.ToInt32(Console.ReadLine());
      area = length * breadth;
      Console.WriteLine();
      Console.WriteLine($"The area of the rectangle is {area }
      square centimetres");
      Console.WriteLine();
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter06 namespace

A window has 5 lines of text. The first and third lines ask for the length and breadth of the rectangle, the second and fourth are the answers, and the fifth states the area of the rectangle.

Figure 25-6

Lab 2 output

Lab 3: Possible Solution with output shown in Figure 25-7

namespace Labs.Chapter06
{
  internal class Lab3
  {
    static void Main(string[] args)
    {
      int length;
      int breadth;
      int height;
      int volume;
      Console.WriteLine("What is the length of the rectangle in
      centimetres");
      length = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("What is the breadth of the rectangle in
      centimetres");
      breadth = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("What is the height of the cuboid in
      centimetres");
      height = Convert.ToInt32(Console.ReadLine());
      volume = length * breadth * height;
      Console.WriteLine();
      Console.WriteLine($"The volume of the cuboid is {volume}
      cubic centimetres");
      Console.WriteLine();
    } // End of Main() method
  } // End of Lab3 class
} //End of Labs.Chapter06 namespace

A window has 7 lines of text. The first, third, and fifth lines ask for the length, breadth, and height of the rectangle, the answers are below each, and the last line states the volume of the cuboid.

Figure 25-7

Lab 3 output

Lab 4: Possible Solution with output shown in Figure 25-8

namespace Labs.Chapter06
{
  /*
  The class holds members (fields) and methods.
  In this example there will only be a main method.
  This is where the application will start running.
  */
  internal class Lab4
  {
    /*
    The Main method is where we will add all our variables and
    write our code. This is only suitable as we are learning to
    program but as we develop our skills we will modularise our
    code i.e. we will break the code up into small methods each
    having only one role. We might not want to declare all our
    variables in the Main method, we may want them to be
    declared inside the smaller methods (chapters). This is where
    we will begin to understand about the scope of variables.
    */
    static void Main(string[] args)
    {
    /*
    A credit card will have a 16-digit number on the front. We
    may wish to include hyphens or spaces between each set of 4
    digits. For this reason, we are making the data type string.
    */
      string creditCardNumber;
    /*
    The month in which the credit card will expire will be
    entered as a number which will be from 0 -12 based on the
    calendar months. This means we can use a byte or sbyte data
    type as it is a small value. The sbyte data type has a
    minimum value of -128 and a maximum value of 127. The byte
    type has a minimum value of 0 and a maximum value of 255.
    A month cannot be a negative, so we use a byte data type.
    */
      byte expiryMonth;
    /*
    The year of expiry only requires the last two digits of the
    year, it will not require the two digits of the century.
    We should use a byte data type as 0 – 255 will be an
    acceptable range for the year.
    */
      byte expiryYear;
    /*
    The card issue number is a one or two digit number on the
    front of the card. Some credit cards will not have an issue
    number. For this example we should expect the user to enter
    a 0 if there is no issue number.
    */
      byte issueNumber;
    /*
    A card verification code (CVC) is also known as the card
    verification value (CVV) and is a security feature used when
    the user is not present to make the payment and present the
    card. It is aimed at reducing fraud.
    */
      int threeDigitCode;
    /*
    A credit card will have a name imprinted on it. This must be
    the exact name used when making a transaction. The name will
    be treated as a string input.
    */
      string nameOnCard;
    //Enter the card holder name as it appears on the card
      Console.WriteLine("Enter your name as it appears " +
        "on your Credit Card");
      nameOnCard = Console.ReadLine();
    /*
    Ask the user to enter the 16-digit credit card number as it
    appears on the credit card and insert hyphens (-) between
    each set of 4 digits. Then use the ReadLine() method to read
    the data input at the console. The input data will be a
    string, so no conversion is necessary as we are assigning
    the value to a variable we declared as data type string.
    */
      Console.WriteLine("Enter the 16 digit credit card number");
      Console.WriteLine("Use hyphens as shown in this " +
        "example to separate each ");
      Console.WriteLine("set of 4 digits  1234-5678-1234-7890");
      creditCardNumber = Console.ReadLine();
    /*
    Ask the user to enter the value of the expiry month. Then use
    the ReadLine() method to read the data input at the console.
    The input data will be a string, so a conversion is necessary
    as we are assigning the value to a variable declared as data
    type byte. We therefore have to use the Convert class and the
    ToByte() method to convert the data read from the console.
    */
      Console.WriteLine("Enter the expiry month number");
      expiryMonth = Convert.ToByte(Console.ReadLine());
    /*
    Ask the user to enter the value of the expiry year. Then use
    the ReadLine() method to read the data input at the console.
    */
      Console.WriteLine("Enter the expiry year number");
      expiryYear = Convert.ToByte(Console.ReadLine());
    /*
    Ask the user to enter the value for the issue number.
    Then use the ReadLine() method to read the data input at the
    console. The input data will be a string so a conversion is
    necessary as we are assigning the value to a variable we
    declared as data type byte. We therefore have to use the
    Convert class and the ToByte() method to convert the data
    read from the console.
    */
      Console.WriteLine("Enter the value for the issue number " +
        " (enter 0 if there is no issue number on our card)");
      issueNumber = Convert.ToByte(Console.ReadLine());
    /*
    Ask the user to enter the value of the 3-digit security code
    that appears on the back of the card. Then use the ReadLine()
    method to read the data input at the console. The input data
    will be a string so a conversion is necessary to assign the
    value to a variable we declared as data type int. We
    therefore have to use the Convert class and the ToInt32()
    method to convert the data read from the console.
    */
     Console.WriteLine("Enter the 3 digit security number " +
      "from the back of the card");
    threeDigitCode = Convert.ToInt32(Console.ReadLine());
    /*
    Now we will display the data we have accepted from the user.
    We use the WriteLine() method from the Console class to
    display the data. The information we have between the
    brackets () of the WriteLine() is a concatenation of a string
    of text between the double quotes "" and a variable. We
    have also used the escape sequence (new line) and the
     (tab) in an attempt to format the display.
    */
    Console.WriteLine("We have entered the following details ");
    Console.WriteLine("************************************* ");
    Console.WriteLine($"Cardholder name: {nameOnCard}");
    Console.WriteLine($"Card number: {creditCardNumber}");
    Console.WriteLine($"Card expiry month: {expiryMonth}");
    Console.WriteLine($"Card expiry year: {expiryYear}");
    Console.WriteLine($"Card issue number: {issueNumber}");
    Console.WriteLine($"Card security code: {threeDigitCode}");
    Console.WriteLine("************************************* ");
    } // End of Main() method
  } // End of Lab4 class
} //End of Labs.Chapter06 namespace

A window has the text, We have entered the following details. Below are details like the cardholder name, card number, and expiry year, among others.

Figure 25-8

Lab 4 output

Chapter 7 Labs: Data Conversion and Arithmetic

Lab 1

Write a C# console application that will calculate the number of points accumulated by a sports team during their season. The program should ask the user to input the number of games won, the number of games drawn, and the number of games lost. The program should total the number of games played and calculate the number of points won based on the facts that 3 points are given for a win, 1 point is given for a draw, and 0 points are given for a lost game. Display the number of games played and the number of points accumulated.

Lab 2

Write a C# console application that will calculate and display
  • The total score for two examinations that a student undertakes

  • The average of the two scores

The two scores will be input by the user at the console and will be accepted as string values by the program code, so conversion will be needed.

Lab 1: Possible Solution with output shown in Figure 25-9

namespace Labs.Chapter07
{
  internal class Lab1
  {
   static void Main(string[] args)
   {
    // Declare the variables
    int numberOfGamesWon, numberOfGamesDrawn, numberOfGamesLost;
    int numberOfGamesPlayed, numberOfPointsAccumulated;
    // Input - accept user input
    Console.WriteLine("How many games were won this season?");
    numberOfGamesWon = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("How many games were drawn this season?");
    numberOfGamesDrawn = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("How many games were lost this season?");
    numberOfGamesLost = Convert.ToInt32(Console.ReadLine());
    // Process - total the number of games played
    numberOfGamesPlayed = numberOfGamesWon +
        numberOfGamesDrawn + numberOfGamesLost;
   /*
    Calculate the number of points based on 3 points for a win
   1 point for a draw and 0 points for a lost game
   */
   numberOfPointsAccumulated = (3 * numberOfGamesWon)
        + numberOfGamesDrawn;
   // Output the details
   Console.WriteLine();
   Console.WriteLine($"The number of games this season was {numberOfGamesPlayed} ");
   Console.WriteLine($"The number of points achieved was {numberOfPointsAccumulated}");
   } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter07 namespace

A window contains 10 lines of text including questions as to how many games were won, drawn, and lost, among others. The answers are given as well.

Figure 25-9

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-10

namespace Labs.Chapter07
{
  internal class Lab2
  {
    static void Main(string[] args)
    {
      int scoreInTestOne, scoreInTestTwo, totalScoreForTwoTests;
      double averageOfTheTwoScores;
      // Input - accept user input for test score one
      Console.WriteLine("What was the score for test one?");
      scoreInTestOne = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("What was the score for test two?");
      scoreInTestTwo = Convert.ToInt32(Console.ReadLine());
      // Process - calculate the total the number of games played
      totalScoreForTwoTests = scoreInTestOne + scoreInTestTwo;
      // Process - calculate the average the two scores
      averageOfTheTwoScores = totalScoreForTwoTests / 2.0;
      // Output the details
      Console.WriteLine("");
      Console.WriteLine($" The total of the two scores is {totalScoreForTwoTests}");
      Console.WriteLine(" ");
      Console.WriteLine($" The average mark for the two tests is { averageOfTheTwoScores}");
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter07 namespace

A window has 8 lines of text including questions as to what the scores are for tests 1, and 2, among others. The answers are given as well.

Figure 25-10

Lab 2 output

Chapter 8 Labs: Arithmetic

Lab 1

Write a C# console application that will simulate a simple payroll program. The program should
  • Allow a user to input the number of hours worked by an employee.

  • Allow a user to input the rate per hour, which the employee is paid.

  • Calculate the gross wage, which is the hours worked multiplied by the rate per hour.

  • Calculate the amount of national insurance to be deducted, where the rate of national insurance is 5% of the gross wage.

  • Calculate the amount of income tax to be deducted, where the formula to be used is 20% of the gross wage after the national insurance has been deducted from the gross wage.

  • Display a simplified wage slip showing, for example, the gross wage, the deductions, and the net pay.

Sample Output Using Test Data
  • How many hours were worked? 40

  • What was the rate per hour? £10.00

  • Payslip
    • Hours – 40

    • Rate – £10.00

    • Gross – £400.00

    • National insurance deductions – £20.00

    • Tax deductions – £76.00

    • Net pay – £304.00

Lab 1: Possible Solution with output shown in Figure 25-11

namespace Labs.Chapter08
{
  internal class Lab1
  {
    static void Main(string[] args)
    {
     // Declare variables required
     int hoursWorked;
     double hourlyRate, nettPay, grossPay;
     double nationalInsuranceDeductions, incomeTaxDeductions;
     double nationalInsuranceRate = 0.05, incomeTaxRate = 0.2;
     // Input Hours Worked
     Console.WriteLine("Enter the number of hours worked: ");
     hoursWorked = Convert.ToInt32(Console.ReadLine());
     // Input Hourly Rate
     Console.WriteLine("Enter Hourly Rate: ");
     hourlyRate = Convert.ToDouble(Console.ReadLine());
     // Process - calculate the net pay
     grossPay = hoursWorked * hourlyRate;
     nationalInsuranceDeductions =
           grossPay * nationalInsuranceRate;
     incomeTaxDeductions =
       (grossPay - nationalInsuranceDeductions) * incomeTaxRate;
  nettPay = grossPay – nationalInsuranceDeductions
        - incomeTaxDeductions;
  // Output simple payslip
  Console.WriteLine($"{"PAYSLIP",22}");
  Console.WriteLine($"===============================");
  Console.WriteLine($"{"Hours Worked",-20} {hoursWorked,10}");
  Console.WriteLine($"{"Hourly Rate",-20} {hourlyRate,10:0.00}");
  Console.WriteLine($"{"Gross Pay",-20} {grossPay,10:0.00}");
  Console.WriteLine($"{"National Insurance",-20}  {nationalInsuranceDeductions,10:0.00}");
  Console.WriteLine($"{"Income Tax",-20}
      {incomeTaxDeductions,10:0.00}");
  Console.WriteLine($"{"=======",31} ");
  Console.WriteLine($"{"Nett Pay",-20} {nettPay,10:0.00}");
  Console.WriteLine($"{"=======",31} ");
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter08 namespace

A window has text for the number of hours worked and the hourly rate. A pay slip below details the hours worked, gross, and net pay, among others.

Figure 25-11

Lab 1 output

Chapter 9 Labs: Selection

Lab 1

Write a C# console application that will ask the user to input a numeric value representing the month of the year, 12, and the number of days in that month will be displayed. Use a switch construct.

Lab 2

Write a C# console application that will ask the user to input the mark achieved by a student in an examination, the maximum mark being 100, and the grade achieved will be displayed. The grade will be determined using the following business logic:
  • Marks greater than or equal to 90 receive Distinction.

  • Marks greater than or equal to 75 receive Pass.

  • Marks lesser less than 75 receive Unsuccessful.

Use an if-else construct.

Lab 3

Write a C# console application that will ask the user to input the name of one of the programming languages – C#, Python, or Java – and a short description of the language will be displayed.

Use an if-else construct and be careful when comparing the String values.

Lab 1: Possible Solution with output shown in Figure 25-12

namespace Labs.Chapter09{
  internal class Lab1{
    static void Main(string[] args){
      int month, daysInMonth = 0;
      Console.WriteLine("Enter the numeric number of the month");
      month = Convert.ToInt32(Console.ReadLine());
      switch (month)
      {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          daysInMonth = 31;
          break;
        case 4:
        case 6:
        case 9:
        case 11:
          daysInMonth = 30;
          break;
        case 2:
          daysInMonth = 28;
          break;
        default:
          Console.WriteLine("Invalid month!");
          break;
      }
      Console.WriteLine($"Month {month} has {daysInMonth} days");
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter09 namespace

A window contains 3 lines of text that read as follows, enter the numeric number of the month, 6, and month 6 has 30 days.

Figure 25-12

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-13

namespace Labs.Chapter09
{
  internal class Lab2
  {
    static void Main(string[] args)
    {
      String grade = null;
      Console.WriteLine("Enter the examination mark: ");
      int mark = Convert.ToInt32(Console.ReadLine());
      if (mark > 0 && mark <= 100)
      {
        if (mark >= 90)
        {
          grade = "Distinction";
        }
        else if (mark >= 75)
        {
          grade = "Pass";
        }
        else
        {
          grade = "Unsuccessful";
        }
        Console.WriteLine($"{mark} marks is a {grade} grade ");
      }
      else
      {
        Console.WriteLine("Mark must be between 1 and 100");
      }
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter09 namespace

A window has 3 lines of text. The first line reads, enter the examination mark, colon, and the second and third, 78, and 78 marks is a pass grade.

Figure 25-13

Lab 2 output

Lab 3: Possible Solution with output shown in Figure 25-14

namespace Labs.Chapter09
{
  internal class Lab3
  {
    static void Main(string[] args)
    {
      String userInputLanguage = null;
      Console.WriteLine("Enter the programming language: ");
      userInputLanguage = Console.ReadLine();
      if (userInputLanguage.Equals("C#"))
      {
        Console.WriteLine("C# is a modern, object-oriented, and"
        + " " + "type-safe programming language. C# enables "
        + " " + "developers to build many types of application"
        + " " + "that run in the .NET ecosystem.");
      }
      else if (userInputLanguage.Equals("Java"))
      {
        Console.WriteLine("Java is a programming language"
                + " " + "released by Sun Microsystems in 1995."
                + " " + "There are lots of applications and "
                + " " + "websites that will not work unless"
                + " " + "Java is installed");
      }
      else if (userInputLanguage.Equals("Python"))
      {
        Console.WriteLine("Python is an interpreted and "
                + " " + "object-oriented programming language");
      }
      else
      {
    Console.WriteLine("Sorry, this is not one of our languages");
      }
      } // End of Main() method
    } // End of Lab3 class
} //End of Labs.Chapter09 namespace

A window has 6 lines of text where the first line reads, enter the programming language, colon. The other lines detail the programming language used.

Figure 25-14

Lab 3 output

Chapter 10 Labs: Iteration

Lab 1

Write a C# console application that will display a table showing a column with pound sterling values (£) and a second column showing the equivalent amount in US dollars ($). The pound amounts should be from £1 to £10, and the exchange rate to be used is $1.25 for each £1.00.

Sample Output
Pound Sterling United States Dollars
1                1.25
2                2.50
3                3.75
4                5.00

Lab 2

Write a C# console application that will display a table showing a column with pound sterling values (£) and a second column showing the equivalent amount in US dollars ($). Remember, reuse code. Lab 1 code might be a great starting point.

The application will ask the user to enter the number of pounds they wish to start their conversion table at and then ask them to enter the number of pounds they wish to stop their conversion table at. The application will display a table showing a column with pound values (£), starting at the user’s start value and ending at the user’s end value, and a second column showing the equivalent amount in US dollars ($). The exchange rate to be used is $1.25 for each £1.00.

Sample Output
Pound Sterling United States Dollars
5                6.25
6                7.50
7                8.75
8                10.00

Lab 3

Write a C# console application that will continually ask the user to input the name of a programming language, and the message “There are many programming languages including (the language input by the user)” will be displayed . The question will stop being asked when the user inputs X as the language. The message should not be displayed when X has been entered. The program will just exit.

Example Output

There are many programming languages including C#.

There are many programming languages including JavaScript.

Lab 4

Write a C# console application that will ask the user to input how many new vehicle registration numbers they wish to input. The application will continually ask the user to input a vehicle registration number until the required number of registrations have been entered. When the vehicle registration number has been entered, a message will display the number of entries that have been made.

Lab 1: Possible Solution with output shown in Figure 25-15

namespace Labs.Chapter10
{
  internal class Lab1
  {
    static void Main(string[] args)
    {
      // Create a variable to hold the dollar amount
      double dollarAmount;
      // Create a constant to hold the exchange rate
      const double dollarsPerPoundRate = 1.25;
      // Display a heading for the columns
      Console.WriteLine($"{"Pounds Sterling",-20} {"United States Dollar",-10}");
      // Iterate 10 times to convert the pounds to dollars
      for (int poundAmount = 1; poundAmount < 11; poundAmount++)
      {
        // Convert pounds to dollars at the rate assigned
        dollarAmount = poundAmount * dollarsPerPoundRate;
        Console.WriteLine($"{poundAmount,-20} {dollarAmount,-10:0.00}");
      }
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter10 namespace

A window has two columns of text with headers, pounds sterling and United States dollar. Each column contains 10 lines of numerical entries.

Figure 25-15

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-16

namespace Labs.Chapter10
{
  internal class Lab2
  {
    static void Main(string[] args)
    {
      // Create a variable to hold the dollar amount
      double dollarAmount;
      // Create variables for the start and end values
      int startValue, endValue;
      // Create a constant to hold the exchange rate
      const double dollarsPerPoundRate = 1.25;
      // Ask the user to input the start value
      Console.WriteLine("What value do you wish to start at?");
      startValue = Convert.ToInt32(Console.ReadLine());
      // Ask the user to input the end value
      Console.WriteLine("What value do you wish to end at?");
      endValue = Convert.ToInt32(Console.ReadLine());
      // Display a heading for the columns
      Console.WriteLine($"{"Pound Sterling",-20} {"United States Dollar",-10}");
      /*
      Iterate starting at the users start value and
      stopping at the users end value
      */
      for (int poundAmount = startValue; poundAmount <= endValue; poundAmount++)
      {
        // Convert pounds to dollars at the rate assigned
        dollarAmount = poundAmount * dollarsPerPoundRate;
        Console.WriteLine($"{poundAmount,-20} {dollarAmount,-10:0.00}");
      } // End of for block
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter10 namespace

A window has questions as to what value you wish to start and end at, and their respective answers. 2 columns below have headers, pound sterling, and United States dollar.

Figure 25-16

Lab 2 output

Lab 3: Possible Solution with output shown in Figure 25-17

using System;
namespace Labs.Chapter10{
  internal class Lab3{
    static void Main(string[] args){
      // Create a variable to hold the user input
      String programmingLanguageInput = null;
      do{
        // Ask the user to input the programming language
        Console.WriteLine("What is the programming language?");
        programmingLanguageInput = Console.ReadLine().ToUpper();
        if (programmingLanguageInput.Equals("X"))
        {
          // Display an end message
          Console.WriteLine("Goodbye");
        }
        else
        {
          // Display a heading for the columns
          Console.WriteLine($"There are many programming " +
            $"languages including {programmingLanguageInput} ");
        }
      } while (!"X".Equals(programmingLanguageInput));
    } // End of Main() method
  } // End of Lab3 class
} //End of Labs.Chapter10 namespace

A window has 9 lines of text. It includes questions about what is the programming language, and the respective answers, among others.

Figure 25-17

Lab 3 output

Lab 4: Possible Solution with output shown in Figure 25-18

namespace Labs.Chapter10
{
  internal class Lab4
  {
    static void Main(string[] args)
    {
      // Create a variable to hold the number of entries
      int numberOfEntriesBeingMade, numberOfEntriesCompleted = 0;
      // Ask the user to input the number of entries being made
      Console.WriteLine("How many new vehicle registrations are you entering?");
      numberOfEntriesBeingMade = Convert.ToInt32(Convert.ToInt32(Console.ReadLine()));
      while (numberOfEntriesBeingMade > numberOfEntriesCompleted)
      {
       // Ask the user to input the vehicle registration number
       Console.WriteLine("What is the vehicle registration number?");
       String vehicleRegistrationNumber = Console.ReadLine();
       // Display a message
       Console.WriteLine($"You have entered {numberOfEntriesCompleted + 1} vehicle registration number which was {vehicleRegistrationNumber} ");
      numberOfEntriesCompleted++;
      }
      Console.WriteLine("Goodbye");
    } // End of Main() method
  } // End of Lab4 class
} //End of Labs.Chapter10 namespace

A window has 9 lines of text. It includes questions about how many new vehicle registrations are entered, and what the registration numbers are, among others.

Figure 25-18

Lab 4 output

Chapter 11 Labs: Arrays

Lab 1

Write a C# console application that will use an array with the claim values: 1000.00, 4000.00, 3000.00, 2000.00. The application should calculate and display the total, average, minimum, and maximum value of the claims.

Lab 2

Write a C# console application that will ask the user to enter four employee names, store them in an array, and then iterate the array to display the names.

Lab 3

Write a C# console application that will read an array that contains a list of staff names alongside their salary and then increase the salary by 10% (1.10), and write the new details to a new array. The application should then iterate the new array and display the employee’s name in column 1 and their new salary in column 1.

The original array should be
{"Gerry Byrne", "20000.00", "Peter Johnston", "30000.00", "Ryan Jones", "50000.00"}
The new array will be
{"Gerry Byrne", "22000.00", "Peter Johnston", "33000.00", "Ryan Jones", "55000.00"}

Lab 1: Possible Solution with output shown in Figure 25-19

using System;
namespace Labs.Chapter11
{
 internal class Lab1
 {
  static void Main(string[] args)
  {
   // Declare the variables to be used
   double maximumValueOfClaims, minimumValueOfClaims;
   double totalValueOfClaims, averageValueOfClaims;
   // Declare and initialise the array of claim values
   double[] claimValues = {1000.00, 4000.00, 3000.00, 2000.00};
   /* Set up a variable for the total of the claim values
      and initialise its value to 0; */
    totalValueOfClaims = 0;
   // Iterate the array and accumulate the claim values
   for (int counter = 0; counter < claimValues.Length; counter++)
   {
  totalValueOfClaims = totalValueOfClaims + claimValues[counter];
   } // End of for block
  // Calculate the average using real arithmetic
  averageValueOfClaims = totalValueOfClaims / claimValues.Length;
  // Display the total and average
  Console.WriteLine($"The total of the claims is " +
    $"£{totalValueOfClaims:0.00} ");
  Console.WriteLine($"The average claim value is" +
    $" £{averageValueOfClaims:0.00} ");
  // Find the maximum value - we assume first value
  // is the maximum value
  maximumValueOfClaims = claimValues[0];
  // Compare all the other numbers to the maximum
  for (int counter = 1; counter < claimValues.Length; counter++)
  {
    // If the next number is greater than the maximum,
    // update the maximum
    if (claimValues[counter] > maximumValueOfClaims)
    {
      maximumValueOfClaims = claimValues[counter];
    }
  } // End of for block
  // Display the maximum claim value
  Console.WriteLine($"The maximum claim value is " +
    $"£{maximumValueOfClaims: 0.00} ");
  // Find the minimum value- we assume the first number
  // is the minimum value
   minimumValueOfClaims = claimValues[0];
  // Compare all the other numbers to the minimum
  for (int counter = 1; counter < claimValues.Length; counter++)
  {
    // If the next number is smaller than the minimum,
    // update the minimum
    if (claimValues[counter] < minimumValueOfClaims)
    {
      minimumValueOfClaims = claimValues[counter];
    }
  } // End of for block
  // Display the minimum claim value
  Console.WriteLine($"The minimum claim value is " +
    $"£{minimumValueOfClaims: 0.00} ");
    } // End of Main() method
  } // End of Lab1 class
} //End of Labs.Chapter11 namespace

A window has 4 lines of text which include the total of the claims, the average, maximum, and minimum claim values. The amounts for each are given.

Figure 25-19

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-20

using System;
namespace Labs.Chapter11{
  internal class Lab2{
    static void Main(string[] args){
      String[] EmployeeNames = new string[4];
      for (int employeenumber = 0; employeenumber < 4; employeenumber++)
      {
        // Ask the user to input the employee name
        Console.WriteLine($"What is the name of employee" +
          $" {employeenumber + 1}? ");
        EmployeeNames[employeenumber] = Console.ReadLine();
      }
      foreach (String name in EmployeeNames)
      {
        Console.WriteLine(name);
      }
    } // End of Main() method
  } // End of Lab2 class
} //End of Labs.Chapter11 namespace

A window has 12 lines of text which include questions as to what the names of employees 1 to 4 are. The answers are given after each question.

Figure 25-20

Lab 2 output

Lab 3: Possible Solution with output shown in Figure 25-21

namespace Labs.Chapter11
{
  internal class Lab3
  {
    static void Main(string[] args)
    {
      // Declare and initialise the array of employees and salary
      String[] employeeAndSalary = { "Gerry Byrne", "20000.00",
        "Peter Johnston", "30000.00", "Ryan Jones", "50000.00" };
      // Declare an array of employees and their new salary
      String[] employeeAndSalaryWithIncrease = new String[employeeAndSalary.Length];
      // Iterate the array and find every 2nd value, the salary
      for (int counter = 0; counter < employeeAndSalary.Length; counter += 2)
      {
        employeeAndSalaryWithIncrease[counter] =  employeeAndSalary[counter];
        // Create a variable of type Double (wrapper class)
        Double newSalary = Convert.ToDouble(employeeAndSalary[counter + 1]) * 1.10;
        // Write the employee name to the new array
        employeeAndSalaryWithIncrease[counter] = employeeAndSalary[counter];
        // Write the Double to the array converting it to String
        employeeAndSalaryWithIncrease[counter + 1] = newSalary.ToString("#.00");
      } // End of for block
      Console.WriteLine($"{"Employee name",-20} " +
        $"{"New Salary",-15} ");
      // Compare all the other numbers to the maximum
      for (int counter = 0; counter < employeeAndSalaryWithIncrease.Length; counter += 2)
      {
        // Display the Employee name and their new salary
        Console.WriteLine($"{employeeAndSalaryWithIncrease[counter],-15} {employeeAndSalaryWithIncrease[counter + 1],15}");
      } // End of for block
    } // End of Main() method
  } // End of Lab3 class
} //End of Labs.Chapter11 namespace

A window has two columns of text with headers, employee name, and new salary. Under employee names are, Gerry Byrne, Peter Johnston, and Ryan Jones.

Figure 25-21

Lab 3 output

Chapter 12 Labs: Methods

Lab 1

Write a C# console application that will use an array with the claim values: 1000.00, 4000.00, 3000.00, 2000.00. The application should use separate VOID methods to
  • Calculate the total of the claim values (void method).

  • Calculate the average of the claim values (void method).

  • Calculate the minimum of the claim values (void method).

  • Calculate the maximum of the claim values (void method).

  • Display a message that states each of the calculated values (void method).

(Refer to Chapter 11 Lab 1 as the code is the same, but it is sequential.)

Lab 2

Use the code from Lab 1 to write a C# console application that will use an array with the claim values: 1000.00, 4000.00, 3000.00, 2000.00. The application should use separate VALUE methods to calculate the
  • Total of the claim values (value method, returns a double)

  • Average of the claim values (value method, returns a double)

  • Minimum of the claim values (value method, returns a double)

  • Maximum of the claim values (value method, returns a double)

and a PARAMETER method that accepts the four calculated values to display a message that states each of the calculated values. This parameter method will not return a value; it is also a void method.

The application should only use variables that are local to the methods we use. The declaration of the array can be at the class level.

Lab 1: Possible Solution with output shown in Figure 25-22

namespace Labs.Chapter12
{
  internal class Lab1
  {
    // Declare and initialise the array of claim
    // values at the class level
    static double[] claimValues = {1000.00,4000.00,3000.00,2000.00};
    /*
     Set up the variables at the class level.
    */
    static double maximumValueOfClaims, minimumValueOfClaims;
    static double totalValueOfClaims, averageValueOfClaims;
    static void Main(string[] args)
    {
      TotalOfClaimValues();
      AverageOfClaimValues();
      MaximumClaimValue();
      MinimumClaimValue();
      DisplayTheCalculatedValues();
    } // End of Main() method
    /*****************************************************
    CREATE THE METHODS OUTSIDE THE MAIN METHOD
    BUT INSIDE THE CLASS
    *****************************************************/
    public static void TotalOfClaimValues()
    {
    // Iterate the array and accumulate the claim values
    for (int counter = 0; counter < claimValues.Length; counter++)
    {
     totalValueOfClaims = totalValueOfClaims + claimValues[counter];
    }
    } // End of TotalOfClaimValues() method
    public static void AverageOfClaimValues()
    {
    // Calculate the average using real arithmetic
    averageValueOfClaims = totalValueOfClaims / claimValues.Length;
    }
    public static void MaximumClaimValue()
    {
      // Find the maximum value - we assume first
      // value is the maximum value
      maximumValueOfClaims = claimValues[0];
      // Compare all the other numbers to the maximum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is greater than the
        // maximum, update the maximum
        if (claimValues[counter] > maximumValueOfClaims)
        {
          maximumValueOfClaims = claimValues[counter];
        }
      }
    } // End of MaximumClaimValue() method
    public static void MinimumClaimValue()
    {
      // Find the minimum value- we assume the
      // first number is the minimum value
      minimumValueOfClaims = claimValues[0];
      // Compare all the other numbers to the minimum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is smaller than the minimum,
        // update the minimum
        if (claimValues[counter] < minimumValueOfClaims)
        {
          minimumValueOfClaims = claimValues[counter];
        }
      }
    } // End of MinimumClaimValue() method
    public static void DisplayTheCalculatedValues()
    {
      // Display the total of the claim values
      Console.WriteLine($"The total of the claims " +
        $"is £{totalValueOfClaims:0.00} ");
      // Display the average of the claim values
      Console.WriteLine($"The average claim value" +
        $" is £{averageValueOfClaims:0.00} ");
      // Display the maximum claim value
      Console.WriteLine($"The maximum claim value is " +
        $"£{ maximumValueOfClaims:0.00} ");
            // Display the minimum claim value
            Console.WriteLine($"The minimum claim value is " +
              $"£{ minimumValueOfClaims:0.00} ");
        }  // End of DisplayTheCalculatedValues() method
  } // End of Lab1 class
} //End of Labs.Chapter12 namespace

A window has 4 lines of text which include the total of the claims, the average, maximum, and minimum claim values. The amounts for each are given.

Figure 25-22

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-23

namespace Labs.Chapter12
{
  internal class Lab2
  {
    // Declare and initialise the array of claim
    // values at the class level
    static double[] claimValues = {1000.00,4000.00,3000.00,2000.00};
    /*
     Set up the variables at the class level.
    */
    static double maximumValueOfClaims, minimumValueOfClaims;
    static double totalValueOfClaims, averageValueOfClaims;
    static void Main(string[] args)
    {
      totalValueOfClaims = TotalOfClaimValues();
      averageValueOfClaims = AverageOfClaimValues();
      maximumValueOfClaims = MaximumClaimValue();
      minimumValueOfClaims = MinimumClaimValue();
      DisplayTheCalculatedValues(totalValueOfClaims,
      averageValueOfClaims,maximumValueOfClaims,
      minimumValueOfClaims);
    } // End of Main() method
/*****************************************************
CREATE THE METHODS OUTSIDE THE MAIN METHOD
BUT INSIDE THE CLASS
*****************************************************/
    public static double TotalOfClaimValues()
    {
      double totalOfClaims = 0.00;
      // Iterate the array and accumulate the claim values
      for (int counter = 0; counter < claimValues.Length; counter++)
      {
        totalOfClaims = totalOfClaims + claimValues[counter];
      }
      return totalOfClaims;
    } // End of TotalOfClaimValues() method
    public static double AverageOfClaimValues()
    {
      double averageOfClaims = 0.00;
      // Calculate the average using real arithmetic
      averageOfClaims = TotalOfClaimValues() / claimValues.Length;
      return averageOfClaims;
    }
    public static double MaximumClaimValue()
    {
      // Find the maximum value - we assume first
      // value is the maximum value
      double maximumOfClaims = claimValues[0];
      // Compare all the other numbers to the maximum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is greater than the maximum,
        // update the maximum
        if (claimValues[counter] > maximumOfClaims)
        {
          maximumOfClaims = claimValues[counter];
        }
      }
      return maximumOfClaims;
    } // End of MaximumClaimValue() method
    public static double MinimumClaimValue()
    {
      // Find the minimum value- we assume the first
      // number is the minimum value
      double minimumOfClaims = claimValues[0];
      // Compare all the other numbers to the minimum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is smaller than the minimum,
        // update the minimum
        if (claimValues[counter] < minimumOfClaims)
        {
          minimumOfClaims = claimValues[counter];
        }
      }
      return minimumOfClaims;
    } // End of MinimumClaimValue() method
    public static void DisplayTheCalculatedValues(
      double totalValueOfClaimsPassedIn,
      double averageValueOfClaimsPassedIn,
      double maximumValueOfClaimsPassedIn,
      double minimumValueOfClaimsPassedIn)
    {
      // Display the total of the claim values
      Console.WriteLine($"The total of the claims is £{totalValueOfClaimsPassedIn:0.00} ");
      // Display the average of the claim values
      Console.WriteLine($"The average claim value is £{ averageValueOfClaimsPassedIn:0.00} ");
      // Display the maximum claim value
      Console.WriteLine($"The maximum claim value is £{ maximumValueOfClaimsPassedIn:0.00} ");
      // Display the minimum claim value
      Console.WriteLine($"The minimum claim value is £{ minimumValueOfClaimsPassedIn:0.00} ");
     }  // End of DisplayTheCalculatedValues() method
  } // End of Lab2 class
} //End of Labs.Chapter12 namespace

A window has 4 lines of text which include the total of the claims, the average, maximum, and minimum claim values. The amounts for each are given.

Figure 25-23

Lab 2 output

Chapter 13 Labs: Classes

Lab 1

Using the code from Chapter 12 Lab 2, write a C# console application that will have
  • A class called CalculatedValues , with no Main() method, and inside it
    • Declare an array with the claim values: 1000.00, 4000.00, 3000.00, 2000.00.

    • Use separate VALUE methods to calculate the
      • Total of the claim values (value method, returns a double)

      • Average of the claim values (value method, returns a double)

      • Minimum of the claim values (value method, returns a double)

      • Maximum of the claim values (value method, returns a double)

    • Declare a PARAMETER method that accepts the four calculated values to display a message that states each of the calculated values. This parameter method will not return a value; it is also a void method.

  • A class called ClaimCalculator , with the Main() method, and inside it
    • Instantiate the CalculatedValues class.

    • Call each of the four value methods and assign the returned values to variables.

    • Pass the four variables to the parameter method, which will display the values.

The application should only use variables that are local to the methods we use. The declaration of the array can be at the class level.

Lab 2

Write a C# console application for an insurance quote that will have
  • A class called QuoteMethodsClass and inside it
    • Create separate methods to ask the user to input
      • Their name

      • The age of their vehicle

      • The engine capacity of their vehicle

        Calculate the quote value based on the following formula:

        100 * (engine capacity/1000) * (10/age of vehicle)

    • Create a method to display the quote amount.

      Example Test 1

      Engine cc 1600

      Age of vehicle 2

      Quote value = 100 * (1600/1000) * (10/2) = 100 * 1.6 * 5 = 800

      Example Test 2

      Engine cc 3000

      Age of vehicle 10

      Quote value = 100 * (3000/1000) * (10/10) = 100 * 3 * 1 = 300

  • A class called QuoteCalculatorClass and inside it
    • Instantiate the QuoteMethodsDetails class.

    • Call each of the five methods.

The display should show the quote amount and the details that were input.

Lab 1: Possible Solution with output shown in Figure 25-24

ClaimCalculator
namespace Labs.Chapter13
{
  internal class ClaimCalculator
  {
    static void Main(string[] args)
    {
    /*
    Set up the variables at the class level.
    */
      double maximumValueOfClaims, minimumValueOfClaims;
      double totalValueOfClaims, averageValueOfClaims;
      // Instantiate the CalculatedValues class
      CalculatedValues myCalculatedValues = new CalculatedValues();
      // Call each method and assign each to a value
      totalValueOfClaims = myCalculatedValues.TotalOfClaimValues();
      averageValueOfClaims = myCalculatedValues.AverageOfClaimValues();
      maximumValueOfClaims = myCalculatedValues.MaximumClaimValue();
      minimumValueOfClaims = myCalculatedValues.MinimumClaimValue();
      // Pass each value to the display method
      myCalculatedValues.DisplayTheCalculatedValues(
      totalValueOfClaims, averageValueOfClaims,
      maximumValueOfClaims, minimumValueOfClaims);
    } // End of Main() method
  } // End of ClaimCalculator class
} //End of Labs.Chapter13 namespace
CalculatedValues
namespace Labs.Chapter13
{
  internal class CalculatedValues
  {
    // Declare and initialise the array of claim
    // values at the class level
    static double[] claimValues = {1000.00,4000.00,3000.00,2000.00};
    /*****************************************************
     CREATE THE METHODS OUTSIDE THE MAIN METHOD
     BUT INSIDE THE CLASS
     *****************************************************/
    public double TotalOfClaimValues()
    {
      double totalOfClaims = 0.00;
      // Iterate the array and accumulate the claim values
      for (int counter = 0; counter < claimValues.Length; counter++)
      {
        totalOfClaims = totalOfClaims + claimValues[counter];
      }
      return totalOfClaims;
    } // End of TotalOfClaimValues() method
    public double AverageOfClaimValues()
    {
      double averageOfClaims = 0.00;
      // Calculate the average using real arithmetic
      averageOfClaims = TotalOfClaimValues() / claimValues.Length;
      return averageOfClaims;
    }
    public double MaximumClaimValue()
    {
      // Find the maximum value - we assume first
      // value is the maximum value
      double maximumOfClaims = claimValues[0];
      // Compare all the other numbers to the maximum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is greater than the maximum,
        // update the maximum
        if (claimValues[counter] > maximumOfClaims)
        {
          maximumOfClaims = claimValues[counter];
        }
      }
      return maximumOfClaims;
    } // End of MaximumClaimValue() method
    public double MinimumClaimValue()
    {
      // Find the minimum value- we assume the first number
      // is the minimum value
      double minimumOfClaims = claimValues[0];
      // Compare all the other numbers to the minimum
      for (int counter = 1; counter < claimValues.Length; counter++)
      {
        // If the next number is smaller than the minimum,
        // update the minimum
        if (claimValues[counter] < minimumOfClaims)
        {
          minimumOfClaims = claimValues[counter];
        }
      }
      return minimumOfClaims;
    } // End of MinimumClaimValue() method
    public void DisplayTheCalculatedValues(
      double totalValueOfClaimsPassedIn,
      double averageValueOfClaimsPassedIn,
      double maximumValueOfClaimsPassedIn,
      double minimumValueOfClaimsPassedIn)
    {
      // Display the total of the claim values
      Console.WriteLine($"The total of the claims is £{totalValueOfClaimsPassedIn:0.00} ");
      // Display the average of the claim values
      Console.WriteLine($"The average claim value is £{averageValueOfClaimsPassedIn:0.00} ");
      // Display the maximum claim value
      Console.WriteLine($"The maximum claim value is £{maximumValueOfClaimsPassedIn:0.00} ");
      // Display the minimum claim value
      Console.WriteLine($"The minimum claim value is £{minimumValueOfClaimsPassedIn:0.00} ");
     }  // End of DisplayTheCalculatedValues() method
  } // End of CalculatedValues class
} //End of Labs.Chapter13 namespace

A window has 4 lines of text which include the total of the claims, the average, maximum, and minimum claim values. The amounts for each are given.

Figure 25-24

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-25

QuoteMethodsClass
namespace Labs.Chapter13
{
  internal class QuoteMethodsClass
  {
    string customerName;
    int ageOfVehicle;
    double engineCapacity,quoteAmount;
    public void AcceptUserName()
    {
      Console.WriteLine("What is the name of the customer?");
      customerName = Console.ReadLine();
    } // End of AcceptUserName() method
    public void AcceptAgeOfVehicle()
    {
      Console.WriteLine("What is the age of the vehicle?");
      ageOfVehicle = Convert.ToInt32(Console.ReadLine());
    } // End of AcceptAgeOfVehicle() method
    public void AcceptEngineCapacityOfVehicle()
    {
      Console.WriteLine("What is the engine capacity?");
      engineCapacity = Convert.ToInt32(Console.ReadLine());
    } // End of AcceptEngineCapacityOfVehicle() method
    public void CalculateQuoteAmount()
    {
     quoteAmount = 100 * (engineCapacity/1000) * (10/ageOfVehicle);
    } // End of CalculateQuoteAmount() method
    public void DisplayQuote()
    {
      Console.WriteLine($"The vehicle to be insured for customer {customerName:0.00} is {ageOfVehicle} years old and has an engine capacity of {engineCapacity}");
      Console.WriteLine($"The quote estimate is £{quoteAmount:0.00}");
    } // End of DisplayQuote() method
  } //End of class QuoteMethodsClass
} // End of namespace Labs.Chapter13
QuoteCalculatorClass
namespace Labs.Chapter13
{
  internal class QuoteCalculatorClass
  {
    static void Main(string[] args)
    {
      QuoteMethodsClass myQuote = new QuoteMethodsClass();
      myQuote.AcceptUserName();
      myQuote.AcceptAgeOfVehicle();
      myQuote.AcceptEngineCapacityOfVehicle();
      myQuote.CalculateQuoteAmount();
      myQuote.DisplayQuote();
    } // End of Main() method
  } //End of class QuoteCalculatorClass
} // End of namespace Labs.Chapter13

A window has 8 lines of text that include questions like the name of the customer, and the age of the vehicle. The answers to the questions are given.

Figure 25-25

Lab 2 output

Chapter 14 Labs: Interfaces

Lab 1

Write a C# console application for an insurance quote that will have
  • An interface called IVehicleInsuranceQuote and inside it there will be
    • An interface method that returns no value, has no parameters, and is called AskForDriverAge

    • An interface method that returns no value, has a parameter of type int to hold the age, and is called AskForVehicleValue

    • An interface method called CalculateQuote that returns no value and has two parameters, one of type int to hold the driver age and the other of type double to hold the vehicle value

  • A class called VehicleInsuranceQuote that implements the IVehicleInsuranceQuote interface and the methods will
    • Ask the user to input their age at their last birthday.

    • Ask the user to input the value of the vehicle being insured.

    • Calculate the monthly premium based on the following formula:

(60/age of driver) * (vehicle value/5000) * 10

Example: 20-year-old driver with a car of value 50000

Monthly premium is (60/20) * (50000/5000) * 10, which is (3) * (10) * 10, which is 300.

  • Have an additional method to display the quote details – driver age, vehicle value, and quote amount.

  • A class called QuoteCalculator with a Main() method that calls the AskForDriverAge() method. The AskForDriverAge() method should call the AskForVehicleValue() method, passing it the age. The AskForVehicleValue() method should call the CalculateQuote() method, passing it the age and value. And the CalculateQuote() method should call the DisplayQuote() method, passing it the age, value, and quote amount.

Lab 1: Possible Solution with output shown in Figure 25-26

Interface - IVehicleInsuranceQuote
namespace Labs.Chapter14
{
  internal interface IVehicleInsuranceQuote
  {
    void AskForDriverAge();
    void AskForVehicleValue(int age);
    void CalculateQuote(int age, double value);
  } // End of interface IVehicleInsuranceQuote
} // End of namespace Labs.Chapter14
VehicleInsuranceQuote Class
namespace Labs.Chapter14
{
  internal class VehicleInsuranceQuote : IVehicleInsuranceQuote
  {
    public void AskForDriverAge()
    {
      Console.WriteLine("What is the age of the driver?");
      int ageOfDriver = Convert.ToInt32(Console.ReadLine());
      AskForVehicleValue(ageOfDriver);
    } // End of AskForDriverAge() method
    public void AskForVehicleValue(int ageOfDriver)
    {
      Console.WriteLine("What is the value of the vehicle?");
      double vehicleValue =  Convert.ToDouble(Console.ReadLine());
      CalculateQuote(ageOfDriver, vehicleValue);
    } // End of AskForVehicleValue() method
    public void CalculateQuote(int ageOfDriver, double vehicleValue)
    {
      double monthlyPremium = (60 / ageOfDriver) * (vehicleValue / 5000) * 10;
      DisplayQuote(ageOfDriver, vehicleValue, monthlyPremium);
    } // End of CalculateQuote() method
    public static void DisplayQuote(int ageOfDriver, double vehicleValue, double monthlyPremium)
    {
      Console.WriteLine($"{"Driver age is:",-20} {ageOfDriver, -20}");
      Console.WriteLine($"{"Vehicle value is:",-20} {vehicleValue,-20}");
      Console.WriteLine($"{"Monthly premium is:",-20} {monthlyPremium,-20}");
    }
  } // End of class VehicleInsuranceQuote
} // End of namespace Labs.Chapter14
QuoteCalculator Class
namespace Labs.Chapter14
{
  internal class QuoteCalculator
  {
    public static void Main(string[] args)
    {
      IVehicleInsuranceQuote VehicleInsuranceQuote = new VehicleInsuranceQuote();
      VehicleInsuranceQuote.AskForDriverAge();
    }// End of Main() method
  } // End of class QuoteCalculator
} // End of namespace Labs.Chapter14

A window has 7 lines of text that include questions about the age of the driver and the value of the vehicle. The answers are given as well.

Figure 25-26

Lab 1 output

Chapter 15 Labs: String Handling

Lab 1

Write a C# console application that will
  • Have a class called Registrations and inside it
    • Declare an array of strings with the following vehicle registrations: ABC 1000, FEA 2222, QWA 4444, FAC 9098, FEA 3344.

    • Have a method to
      • Find all vehicle registrations beginning with an F and display them in the console window.

Lab 2

Write a C# console application that will
  • Have a class called ClaimsPerState and inside it
    • Declare an array of strings with the following claim details: 1000IL, 2000FL, 1500TX, 1200CA, 2000NC, 3000FL.

  • Have separate methods to
    • Display the full array of claim details in alphabetical order.

    • Check whether a given string ends with the contents of another string and, if it does, write it to the console. In this example we will look for the string FL.

    • Read the claim values and find the total of all the claim values given that the claim values are the first four numbers in the claim string.

Lab 1: Possible Solution with output shown in Figure 25-27

namespace Labs.Chapter15
{
  internal class Registrations
  {
    static void Main(string[] args)
    {
     string[] vehicleRegistrations = {"ABC 1000", "FEA 2222", "QWA 4444","FAC 9098", "FEA 3344"};
   // Call the method that will find the registration
      AllRegistrationsBeginningWithSpecifiedLetter(vehicleRegistrations,'F');
    } // End of Main() method
    public static void AllRegistrationsBeginningWithSpecifiedLetter(string[] vehicleRegistrations, char letterInRegistration)
  {
  Console.WriteLine("Registrations beginning with character F");
  // Iterate the array
 for (int counter = 0; counter < vehicleRegistrations.Length; counter++)
    {
      // Check if the current element starts with the letter
      if (vehicleRegistrations[counter].StartsWith(letterInRegistration))
      {
        Console.WriteLine(vehicleRegistrations[counter]);
      }
    }
  }//End of allRegistrationsBeginningWithSpecifiedLetter() method
  } // End of Registrations class
} //End of Labs.Chapter15 namespace

A window has 4 lines of text where the first line reads as, registrations beginning with F. The next three lines are registration numbers.

Figure 25-27

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-28

Claims Per State
namespace Labs.Chapter15
{
  internal class ClaimsPerState
  {
    static void Main(string[] args)
    {
      string[] claimsWithStateAbbreviation = {"1000IL", "2000FL", "1500TX","1200CA", "2000NC", "0300FL"};
      // Call the DisplayTheSortedClaims() method
      Console.WriteLine("The sorted array elements are");
      DisplayTheSortedClaims(claimsWithStateAbbreviation);
      // Declare the state to be found
      string stateAbbreviationToFind = "FL";
      // Call the AllClaimsInASpecificState() method
      // passing it the string to be found
      Console.WriteLine($"The claims for the state of {stateAbbreviationToFind} are ");
      AllClaimsInASpecificState(stateAbbreviationToFind, claimsWithStateAbbreviation);
      // Call the FindTheTotalOfAllClaimValues() method
      double totalOfAllClaims = FindTheTotalOfAllClaimValues(claimsWithStateAbbreviation);
      Console.WriteLine($"The total of the claim values is {totalOfAllClaims:0.00}");
    } // End of Main() method
    public static void AllClaimsInASpecificState(string stateAbbreviationToFind, string[] claimsWithStateAbbreviation)
    {
      // Iterate the array
      for (int counter = 0; counter < claimsWithStateAbbreviation.Length; counter++)
      {
        // Check if the current element of the array ends with
        // the letter passed to the method
        if (claimsWithStateAbbreviation[counter].EndsWith(stateAbbreviationToFind))
        {
          Console.WriteLine(claimsWithStateAbbreviation[counter]);
        }
      }
    } // End of AllClaimsInASpecificState() method
    public static void DisplayTheSortedClaims(string[] claimsWithStateAbbreviation)
    {
      // Sort the claimsWithStateAbbreviation array
      Array.Sort(claimsWithStateAbbreviation);
      // Iterate the sorted array using the foreach construct
      foreach (string claim in claimsWithStateAbbreviation)
      {
        Console.WriteLine(claim);
      }
    } // End of DisplayTheSortedClaims() method
    public static double FindTheTotalOfAllClaimValues(string[] claimsWithStateAbbreviation)
    {
      double currentTotalValue = 0.00;
      double claimValue = 0.00;
      String firstFourCharacters;
      // Iterate the array
      for (int counter = 0; counter < claimsWithStateAbbreviation.Length; counter++)
      {
      /*
      Read the first four characters of the array element, parse
      (convert) it to a double and add it to the current total
      */
        firstFourCharacters = claimsWithStateAbbreviation[counter].Substring(0, 4);
        claimValue = Double.Parse(firstFourCharacters);
        currentTotalValue += claimValue;
      }
      return currentTotalValue;
    } // End of FindTheTotalOfAllClaimValues() method
  } // End of ClaimsPerState class
} //End of Labs.Chapter15 namespace

A window has 11 lines of text which include entries under sorted array elements and claims for the state of F L. The total claims value is given.

Figure 25-28

Lab 2 output

Chapter 16 Labs: File Handling

Lab 1

Write a C# console application that will
  • Have a class called WriteRegistrationsToFile.

  • Ask a user to input five vehicle registrations with the following format: three letters followed by a space followed by four numbers, for example, ABC 1234.

  • Write each of the five vehicle registrations to a new line in a text file called vehicleregistrations.txt.

Lab 2

Write a C# console application that will
  • Have a class called ReadRegistrationsFromFile.

  • Declare an array of strings called vehicleRegistrations.

  • Read the five lines from the vehicleregistrations.txt file created in Lab 1 and add them to the array.

  • Iterate the array and display each vehicle registration.

Lab 1: Possible Solution with output shown in Figure 25-29

WriteRegistrationsToFile
namespace Labs.Chapter16
{
  internal class WriteRegistrationsToFile
  {
    static void Main(string[] args)
    {
      string vehicleRegistration;
      // Assign the name of the file to be used to a variable.
      string filePath = "vehicleregistrations.txt";
      /*
      Create a loop to iterate 5 times asking the user
      to input a vehicle registration each time.
      */
      for (int counter = 1; counter < 6; counter++)
      {
       Console.WriteLine($"Enter registration number {counter}");
       vehicleRegistration = Console.ReadLine();
       WriteRegistrationToTextFile(vehicleRegistration, filePath);
      } // Enter of iteration
    }  // End of Main() method
    public static void WriteRegistrationToTextFile(String vehicleRegistration, string filePath)
    {
      // Enclose the code in a try catch to handle errors
      try
      {
        // Create a FileStream with mode CreateNew
        FileStream stream = new FileStream(filePath, FileMode.Create);
        // Create a StreamWriter from FileStream
        using (StreamWriter writer = new StreamWriter(stream))
        {
          writer.WriteLine(vehicleRegistration);
        }
      } // End of try block
      catch (Exception ex)
      {
        Console.WriteLine($"Error writing file {filePath} error was {ex}");
      } // End of the catch section of the error handling
    } // End of the writeRegistrationToTextFile() method
  } // End of WriteRegistrationsToFile class
} //End of Labs.Chapter16 namespace

A window has 10 lines of text for registration number entries 1 to 5. On the right is a folder tree with the file, vehicle registrations dot t x t, highlighted.

Figure 25-29

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-30

ReadRegistrationsFromFile
namespace Labs.Chapter16
{
  internal class ReadRegistrationsFromFile
  {
    static void Main(string[] args)
    {
      // Assign the name of the file to be used to a variable.
      string filePath = "vehicleregistrations.txt";
      // Declare and create an array to hold the 5 registrations
      string[] vehicleRegistrations = new string[5];
      ReadRegistrationFromTextFile(vehicleRegistrations, filePath);
      DisplayArrayItems(vehicleRegistrations);
    }// End of Main() method
    public static void ReadRegistrationFromTextFile(string[] vehicleRegistrations, string filePath)
    {
      // Set up a string variable to hold the lines read
      string line = null;
      int lineCountValue = 0;
      // Create a StreamReader from a FileStream
      using (StreamReader reader =
        new StreamReader(new FileStream(filePath,FileMode.Open)))
      {
        // Read line by line
        while ((line = reader.ReadLine()) != null)
        {
          vehicleRegistrations[lineCountValue] = line;
          lineCountValue++;
        }
      } // End of using block
    } // End of the ReadRegistrationFromTextFile() method
    public static void DisplayArrayItems(string[] vehicleRegistrations)
    {
      // Iterate the sorted array using the foreach construct
      foreach (string vehicleRegistration in vehicleRegistrations)
      {
        Console.WriteLine(vehicleRegistration);
      }
    } // End of DisplayArrayItems() method
  } // End of ReadRegistrationsFromFile class
} //End of Labs.Chapter16 namespace

A window is titled, vehicle registrations dot t x t. A console is open on its right with a list of vehicle registration numbers.

Figure 25-30

Lab 2 output

Chapter 17 Labs: Exceptions

Lab 1

Write a C# console application that will
  • Have a class called OutOfBoundsException, which will contain a Main() method that will have code to
    • Declare an array of integers called claimValues containing the following claim values: 1000, 9000, 0, 4000, 5000.

    • Iterate the array of values and display each value to the console.

    • Have a try block that contains the code to display the sixth array item.

    • Have a catch block that will catch an IndexOutOfRangeException and display the exception message.

Lab 2

Write a C# console application that extends the code from Lab 1. The application will
  • Have a class called MultipleTryCatch, which will contain a Main() method that will have code to
    • Declare an array of integers called claimValues containing the following claim values: 1000, 9000, 0, 4000, 5000.

    • Have a try block that contains the code to iterate the array of values and divide each value into 10000 displaying the answer in the console.

    • Have a catch block that will catch an IndexOutOfRangeException and display the exception message.

    • Have a catch block that will catch a DivideByZeroException and display the exception message.

    • Have a finally block that will display a message to say “In finally block tidying up”.

Lab 1: Possible Solution with output shown in Figure 25-31

namespace Labs.Chapter17
{
 internal class OutOfBoundsException
 {
 public static void Main(string[] args)
 {
 int[] claimValues = { 1000, 9000, 0, 4000, 5000 };
 for (int i = 0; i < claimValues.Length; i++)
 {
   Console.WriteLine(claimValues[i]);
 }
 try
 {
   // Write a value which is outside the array upper limit
   Console.WriteLine(claimValues[5]);
 }
 catch (IndexOutOfRangeException ex)
 {
  // Display the exception message received
    Console.WriteLine($"Exception is - {ex.Message}");
  }
 }// End of Main() method
} // End of OutOfBoundsException class
} //End of Labs.Chapter17 namespace

A window has 6 lines. The first 5 lines are number entries, and the last line reads, exception is, dash, index was outside the bounds of the array.

Figure 25-31

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-32

namespace Labs.Chapter17{
  internal class MultipleTryCatch{
    public static void Main(string[] args){
      int[] claimValues = { 1000, 9000, 0, 4000, 5000 };
      try
      {
        // Divide each array vale into 10000
        for (int i = 0; i < claimValues.Length; i++)
        {
     Console.Write($"Dividing 10000 by {claimValues[i]} gives ");
          Console.WriteLine($"{10000 / claimValues[i]}");
        }
       // Write a value which is outside the array upper limit
       Console.WriteLine(claimValues[5]);
      }
      catch (IndexOutOfRangeException ex)
      {
       // Display the exception message received
       Console.WriteLine($"Exception is {ex.Message}");
      }
      // Catch block to catch the divide by zero exception
      catch (DivideByZeroException ex)
      {
     Console.WriteLine($"an exception - {ex.Message}");
      }
      // Finally block to tidy up etc, this block always runs
      finally
      {
          Console.WriteLine(" In finally block tidying up");
      }
    }// End of Main() method
  } // End of OutOfBoundsException class
} //End of Labs.Chapter17 namespace

A window has 4 lines of text. The first 3 lines are about dividing 10000 by 1000, 9000, and 0, respectively, along with their answers.

Figure 25-32

Lab 2 output

Chapter 18 Labs: Serialization of a Class

Lab 1

Write a C# console application that will
  • Have a class called Vehicle, which implements Serializable.

    The Vehicle class will have
    • Two private string properties called vehicleManufacturer and vehicleType

    • One private nonserialized property called vehicleChassisNumber

    • A constructor using all three properties

    • Getters and setters for the properties

  • Have a class called VehicleJson, which will
    • Instantiate the Vehicle class and pass details of a vehicle to the constructor, for example:

      Vehicle myVehicle = new Vehicle("Ford", "Mondeo", "VIN 1234567890");

    • Write the serialized data to a file called vehicleserialized.ser.

    • Read the serialized data file and display the vehicle details.

Lab 2

Write a C# console application that will
  • Have a class called AgentEntity , which implements Serializable
    • The AgentEntity class will have
      • The following private properties:
        • agentNumber, which is of data type int

        • agentYearsOfService, which is of data type int

        • agentFullName, which is of data type string

      • The following private nonserialized properties:
        • agentDOB, which is of data type string

        • agentCapitalInvestment, which is of data type double

    • A constructor using all the properties

    • Getters and setters for all the properties

  • Have a class called AgentJson, which will
    • Instantiate the AgentEntity class and pass details of an agent to the constructor, for example:
      AgentEntity myAgentEntity = new AgentEntity(190091, 25, "Gerry Byrne", "01/01/1970", 50000.00);
    • Write the serialized data to a file called agentserialized.ser.

    • Read the serialized data file and display the agent details.

Lab 1: Possible Solution with output shown in Figure 25-33

Vehicle Class (Entity)
using System.Text.Json.Serialization;
namespace Labs.Chapter18
{
  [Serializable]
  internal class Vehicle
  {
    // Members of the class.
    // [JsonIgnore] members are not serialised
    private string vehicleManufacturer;
    private string vehicleType;
    // Example for [NonSerialized]
    [JsonIgnore] private String vehicleChassisNumber;
    public string VehicleManufacturer
    {
      get => vehicleManufacturer; set => vehicleManufacturer = value;
    }
    public string VehicleType
    {
      get => vehicleType; set => vehicleType = value;
    }
    public string VehicleChassisNumber
    {
      get => vehicleChassisNumber; set => vehicleChassisNumber = value;
    }
    public Vehicle(string vehicleManufacturer, string vehicleType, string vehicleChassisNumber)
    {
      this.VehicleManufacturer = vehicleManufacturer;
      this.VehicleType = vehicleType;
      this.VehicleChassisNumber = vehicleChassisNumber;
    } // End of constructor
  } // End of Vehicle class
} // End of namespace Labs.Chapter18
VehicleJson Serialization and Read Class
using System.Text.Json;
namespace Labs.Chapter18
{
  internal class VehicleJson
  {
    public static async Task Main()
    {
      string filePath = "vehicleserialized.ser";
      Vehicle myVehicle = new Vehicle("Ford", "Mondeo", "VIN 1234567890");
      //Serialize
      string jsonString = JsonSerializer.Serialize<Vehicle>(myVehicle);
      Console.WriteLine(jsonString);
      await CreateJSON(myVehicle, filePath);
      ReadJSON(filePath);
    } // End of Main() method
    public static async Task CreateJSON(Vehicle myVehicle, string filePath)
    {
      using FileStream createStream = File.Create(filePath);
      await JsonSerializer.SerializeAsync(createStream, myVehicle);
      createStream.Close();
      await createStream.DisposeAsync();
      Console.WriteLine(File.ReadAllText(filePath));
    } // End of CreateJSON() method
    public static void ReadJSON(string filePath)
      using FileStream myStream = File.OpenRead(fileName);
      Vehicle myVehicle = JsonSerializer.Deserialize<Vehicle>(myStream);
      Console.WriteLine("Vehicle Details");
      Console.WriteLine("Vehicle Name: " + myVehicle.VehicleManufacturer);
      Console.WriteLine("VehicleVehicle Age: " + myVehicle.VehicleType);
      Console.WriteLine("Customer Account No: " + myVehicle.VehicleChassisNumber);
    } // End of ReadJSON() method
  } // End of class VehicleJson
} // End of namespace

A 5-line code on the left mentions the vehicle manufacturer, type, and chassis number. A tree folder on the right has the file, vehicle serialized dot s e r, highlighted.

Figure 25-33

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-34

AgentEntity Class
using System.Text.Json.Serialization;
namespace Labs.Chapter18
{
  [Serializable]
  internal class AgentEntity
  {
  /*
  Members of the class are private as we have getters and
  setters and we have two [NonSerialized] members as we do
  not want them to be serialised
  */
    private int agentNumber;
    private int agentYearsOfService;
    private string agentFullName;
    [JsonIgnore] private String agentDOB;
    [JsonIgnore] private double agentCapitalInvestment;
    public AgentEntity(int agentNumber, int agentYearsOfService,
      string agentFullName, string agentDOB,
      double agentCapitalInvestment)
    {
      this.agentNumber = agentNumber;
      this.agentYearsOfService = agentYearsOfService;
      this.agentFullName = agentFullName;
      this.agentDOB = agentDOB;
      this.agentCapitalInvestment = agentCapitalInvestment;
    } // End of AgentEntity constructor
    public int AgentNumber
    {
      get => agentNumber;
      set => agentNumber = value;
    }
    public int AgentYearsOfService
    {
      get => agentYearsOfService;
      set => agentYearsOfService = value;
    } // End of AgentYearsOfService property
    public string AgentFullName
    {
      get => agentFullName;
      set => agentFullName = value;
    } // End of AgentFullName property
    public string AgentDOB
    {
      get => agentDOB;
      set => agentDOB = value;
    } // End of AgentDOB property
    public double AgentCapitalInvestment
    {
      get => agentCapitalInvestment;
      set => agentCapitalInvestment = value;
    } // End of AgentCapitalInvestment property
  }// End of class AgentEntity
} // End of namespace Labs.Chapter18
AgentJson Serialization and Read Class
using System.Text.Json;
namespace Labs.Chapter18
{
  internal class AgentJson
  {
    public static async Task Main()
    {
      string filePath = "agentserialized.ser";
      AgentEntity myAgent = new AgentEntity(190091, 25, "Gerry Byrne", "01/01/1970", 50000.00);
      //Serialize
      string jsonString = JsonSerializer.Serialize<AgentEntity>(myAgent);
      Console.WriteLine(jsonString);
      await CreateJSON(myAgent, filePath);
      ReadJSON(filePath);
    } // End of Main() method
    public static async Task CreateJSON(AgentEntity myAgent, string filePath)
    {
      using FileStream createStream = File.Create(filePath);
      await JsonSerializer.SerializeAsync(createStream, myAgent);
      createStream.Close();
      await createStream.DisposeAsync();
      Console.WriteLine(File.ReadAllText(filePath));
    } // End of CreateJSON() method
    public static void ReadJSON(string filePath)
    {
      using FileStream myStream = File.OpenRead(filePath);
      AgentEntity myAgent = JsonSerializer.Deserialize<AgentEntity>(myStream);
      Console.WriteLine("Agent Details");
      Console.WriteLine("Agent Number: " + myAgent.AgentNumber);
      Console.WriteLine("Years of service: " + myAgent.AgentYearsOfService);
      Console.WriteLine("Full Name: " + myAgent.AgentFullName);
      Console.WriteLine("Date of birth: " + myAgent.AgentDOB);
      Console.WriteLine("Investment: " + myAgent.AgentCapitalInvestment);
    } // End of ReadJSON() method
  } // End of class VehicleJson
} // End of namespace

A window has a 3-line code on top mentioning agent details. Below are the agent details which include the agent number, and full name, among others.

Figure 25-34

Lab 2 output

Chapter 19 Labs: Structs

Lab 1

Write a C# console application that will
  • Have a class called AutoInsurance , which will have
    • A struct called Vehicle, which will have
      • Variables to hold the vehicle manufacturer, chassis number, color, and engine capacity

      • A constructor that accepts values for all four variables

      • Getters and setters for the variables

      • A method to display the manufacturer name

      • A method to display the engine capacity

  • Have a Main() method that will have code to
    • Instantiate the Vehicle struct and pass details of a vehicle to the constructor, for example:
      Vehicle myVehicle = new Vehicle("Ford", "VIN 1234567890", "Blue",1600);
    • Call the method that displays the manufacturer name.

    • Call the method that displays the engine capacity.

Lab 2

Write a C# console application that will
  • Have a class called PropertyInsurance , which will have
    • A struct called Apartment, which will have
      • Variables to hold the number of rooms, area of the floor, and the estimated value

      • A constructor that accepts values for all three variables

      • A constructor that accepts values for the number of rooms variable and the area of the floor variable and sets the estimated value to be 1000000

      • A method to display a message stating the values of the three struct members

  • Have a Main() method that will have code to
    • Instantiate an Apartment struct and pass details of an apartment with all three values to the constructor, for example:

    Apartment studioOne= new Apartment(2, 50, 120000);
    • Instantiate an Apartment struct and pass details of an apartment with only two values to the constructor, for example:

    Apartment studioTwo= new Apartment(3, 60);
    • Call the method that displays the apartment details for studioOne.

    • Call the method that displays the apartment details for studioTwo.

Lab 1: Possible Solution with output shown in Figure 25-35

namespace Labs.Chapter19
{
  internal class AutoInsurance
  {
    struct Vehicle
    {
      //Variables
      string vehicleManufacturer;
      string vehicleChassisNumber;
      string vehicleColor;
      int vehicleEngineCapacity;
      // Custom constructor
      public Vehicle(string vehicleManufacturer,
        string vehicleChassisNumber, string vehicleColor,
        int vehicleEngineCapacity)
      {
        this.vehicleManufacturer = vehicleManufacturer;
        this.vehicleChassisNumber = vehicleChassisNumber;
        this.vehicleColor = vehicleColor;
        this.vehicleEngineCapacity = vehicleEngineCapacity;
      }
      //Properties for the struct variable - getters and setters
      public string VehicleManufacturer
      {
        get => vehicleManufacturer;
        set => vehicleManufacturer = value;
      }
      public string VehicleChasisNumber
      {
        get => vehicleChassisNumber;
        set => vehicleChassisNumber = value;
      }
      public string VehicleColor
      {
        get => vehicleColor;
        set => vehicleColor = value;
      }
      public int VehicleEngineCapacity
      {
        get => vehicleEngineCapacity;
        set => vehicleEngineCapacity = value;
      }
      // Methods of the struct
      public void DisplayManufacturerName()
      {
        Console.WriteLine($"The vehicle manufacturer is {vehicleManufacturer}");
      } // End of DisplayManufacturerName() method
      public void DisplayEngineCapacity()
      {
        Console.WriteLine($"The engine capacity is {vehicleEngineCapacity}");
      } // End of DisplayEngineCapacity() method
    } // End of the Vehicle struct
    // Main method code for the AutoInsurance class
    static void Main(string[] args)
    {
      Vehicle myVehicle = new Vehicle("Ford", "VIN 1234567890", "Blue", 1600);
      myVehicle.DisplayManufacturerName();
      myVehicle.DisplayEngineCapacity();
    } // End of Main() method
  } // End of class AutoInsurance
} // End of namespace Labs.Chapter19

A window has 2 lines of text where the first line reads as follows, the vehicle manufacturer is Ford. The second line reads the engine capacity is 1600.

Figure 25-35

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-36

namespace Labs.Chapter19
{
  internal class PropertyInsurance
  {
    public struct Apartment
    {
      int numberOfRooms;
      int floorArea;
      double estimatedValue;
      // Members are initialized using the constructor
      public Apartment(int numberOfRooms, int floorArea,
        double estimatedValue)
      {
        this.numberOfRooms = numberOfRooms;
        this.floorArea = floorArea;
        this.estimatedValue = estimatedValue;
      } // End of the first constructor
      // A second constructor to initialize 1 member that has not
      // been given a value in this form of the constructor
      public Apartment(int numberOfRooms, int floorArea)
      {
        this.numberOfRooms = numberOfRooms;
        this.floorArea = floorArea;
        this.estimatedValue = 1000000.00;
      } // End of the second constructor
      public void DisplayValues()
      {
        Console.WriteLine($"The apartment has {this.numberOfRooms.ToString()} rooms");
        Console.WriteLine($"The floor area of the apartment is {this.floorArea.ToString()} square metres");
        Console.WriteLine($"The estimated value of the apartment is {this.estimatedValue.ToString()}");
        Console.WriteLine();
      } // End of the DisplayValues() method
    } // End of the struct Apartment
    static void Main(string[] args)
    {
      Apartment studioOne = new Apartment(2, 50, 120000.00);
      Apartment studioTwo = new Apartment(3, 60 );
      studioOne.DisplayValues();
      Console.WriteLine();
      Console.WriteLine("This apartment was not been given an estimated value so the constructor that has been used has set the value as 1000000");
      Console.WriteLine();
      studioTwo.DisplayValues();
    }  // End of the Main() method
  } // End of the class PropertyInsurance
} // End of the namespace Labs.Chapter19

A window has 9 lines of text. The details of apartments are given like the number of rooms, floor area, and estimated value, among others.

Figure 25-36

Lab 2 output

Chapter 20 Labs: Enumerations

Lab 1

Write a C# console application that will
  • Have a class called AutoInsurance, which will have
    • An enumeration called Manufacturer, which will have the values Ford, Chevrolet, Jeep, and Honda

    • An enumeration called Color, which will have the values Red, Blue, and Green

    • A struct called Vehicle, which will have
      • Variables to hold the vehicle manufacturer of enum type Manufacturer and the vehicle color of enum type Color

      • A constructor that accepts values for the two variables of enum type Manufacturer and enum type Color

      • A method to display the manufacturer name and the vehicle color

  • Have a Main() method that will have code to
    • Instantiate a Vehicle struct and pass details of a vehicle to the constructor, for example:

    Vehicle myVehicleOne = new Vehicle(Manufacture.Ford, Color.Blue);
    • Call the method that displays the vehicle details.

    • Instantiate a Vehicle struct and pass details of a vehicle to the constructor, for example:

Vehicle myVehicleTwo = new Vehicle(Manufacture.Jeep, Color.Green);
  • Call the method that displays the vehicle details.

Lab 2

Write a C# console application that will
  • Have a class called PropertyInsurance, which will have
    • An enumeration called InsuranceRiskEnum, which will have the values Low = 1, Medium = 10, and High = 20

    • An enumeration called LocationFactorEnum, which will have the values NotNearRiver, NearRiver

    • An enumeration called PropertyTypeEnum, which will have the values Bungalow, House, and Apartment

    • Have a Main() method that will have code to
      • Call an AskForPropertyType() method that returns an int and assign it to a variable of type int called propertyType.

        The method will display a menu and return the integer value entered:
        Console.WriteLine("What is the property type, 1 2 or 3?");
        Console.WriteLine("1. Bungalow ");
        Console.WriteLine("2. House");
        Console.WriteLine("3. Apartment");
        int  propertyType = Convert.ToInt32(Console.ReadLine());
        return propertyType;
      • Call an AskForPropertyLocation() method that returns a string and assign it to a variable of type string called isNearARiver.

        The method will ask if the property is within 50 meters of a river and returns the value entered, either Y or N:
        Console.WriteLine("Is the property within 50 metres " +
        "of a river?");
        string nearARiver = Console.ReadLine();
        return nearARiver;
      • Call an AskForPropertyValue() method that returns a double and assign it to a variable of type double called estimatedValue.

        The method will ask for the property value and return the estimated value:
        Console.WriteLine("What is the estimated value of " +
        "the property?");
        double estimatedValue = Convert.ToDouble(Console.ReadLine());
        return estimatedValue;
      • Call the method QuoteAmount(), passing it the values for the propertyType, isNearARiver, and estimatedValue.

        Calculate the quote amount based on the following formula:

      double quoteAmount = (propertyTypeRiskFactor *
      (propertyValue / 10000) * locationFactor

      The propertyTypeRiskFactor is based on the property type in the enum InsuranceRiskEnum Bungalow is High, House is Medium, and Apartment is Low.

      The locationFactor is whether the property is located near a river and uses the enum LocationFactorEnum Y (Yes) is 10, N (No) is 1.
      • Call the method that displays the quote details.

Lab 1: Possible Solution with output shown in Figure 25-37

using System;
namespace Labs.Chapter20
{
  internal class AutoInsurance
  {
    public enum Manufacturer
    {
      Ford,
      Chevrolet,
      Jeep,
      Honda
    }
    public enum Color
    {
      Red,
      Blue,
      Green
    }
    struct Vehicle
    {
      //Variables
      Manufacturer vehicleManufacturer;
      Color vehicleColor;
      // Custom constructor
      public Vehicle(Manufacturer vehicleManufacturer, Color vehicleColor)
      {
        this.vehicleManufacturer = vehicleManufacturer;
        this.vehicleColor = vehicleColor;
      }
      // Methods of the struct
      public void DisplayVehiclerDetails()
      {
        Console.WriteLine($"The vehicle manufacturer is {vehicleManufacturer}");
        Console.WriteLine($"The vehicle color is {vehicleColor}");
      } // End of DisplayVehiclerDetails() method
    } // End of the Vehicle struct
    // Main method code for the AutoInsurance class
    static void Main(string[] args)
    {
      Vehicle myVehicleOne =
        new Vehicle(Manufacturer.Ford,Color.Blue);
      myVehicleOne.DisplayVehiclerDetails();
      Console.WriteLine();
      Vehicle myVehicleTwo =
        new Vehicle(Manufacturer.Jeep, Color.Green);
      myVehicleTwo.DisplayVehiclerDetails();
    } // End of Main() method
  } // End of class AutoInsurance
} // End of namespace Labs.Chapter20

A window has 4 lines of text. The first and third lines mention the vehicle manufacturers, and in the second and fourth, the colors of the vehicles.

Figure 25-37

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-38

using System;
namespace Labs.Chapter20
{
  internal class PropertyInsurance
  {
    public enum InsuranceRiskEnum
    {
      Low = 1,
      Medium = 10,
      High = 20,
    }
    public enum LocationFactorEnum
    {
      NotNearRiver = 1,
      NearRiver = 10,
    }
    public enum PropertyTypeEnum
    {
      Bungalow,
      House,
      Apartment
    }
    static void Main(string[] args)
    {
      int propertyType = AskForPropertyType();
      string isNearARiver = AskForPropertyLocation();
      double estimatedValue = AskForPropertyValue();
      QuoteAmount(propertyType, isNearARiver, estimatedValue);
    } // End of Main() method
    public static int AskForPropertyType()
    {
      Console.WriteLine("What is the property type, 1 2 or 3?");
      Console.WriteLine("1. Bungalow ");
      Console.WriteLine("2. House");
      Console.WriteLine("3. Apartment");
      int  propertyType = Convert.ToInt32(Console.ReadLine());
      return propertyType;
    } // End of PropertyType() method
    public static string AskForPropertyLocation()
    {
      Console.WriteLine("Is the property within 50 metres " +
        "of a river?");
      string nearARiver = Console.ReadLine();
      return nearARiver;
    } // End of PropertyLocation() method
    public static double AskForPropertyValue()
    {
      Console.WriteLine("What is the estimated value of " +
        "the property?");
   double estimatedValue = Convert.ToDouble(Console.ReadLine());
      return estimatedValue;
    } // End of PropertyValue() method
 public static int PropertyLocationRiskFactor(string nearRiver)
    {
      int locationFactor;
      if (nearRiver.Equals("Y"))
      {
       locationFactor = (int)LocationFactorEnum.NearRiver;
      }
      else
      {
        locationFactor = (int)LocationFactorEnum.NotNearRiver;
      }
      return locationFactor;
    } // End of PropertyRiskFactor() method
    public static void QuoteAmount(int propertyType,
      string isPropertyNearARiver, double propertyValue)
    {
      int propertyTypeRiskFactor;
      switch (propertyType)
      {
        case 1:
          propertyTypeRiskFactor = (int)InsuranceRiskEnum.High;
          break;
        case 2:
          propertyTypeRiskFactor = (int)InsuranceRiskEnum.Medium;
          break;
        case 3:
          propertyTypeRiskFactor = (int)InsuranceRiskEnum.Low;
          break;
        default:
          propertyTypeRiskFactor = 9999;
          break;
      }
      double quoteAmount = (propertyTypeRiskFactor
           * (propertyValue / 10000)
           * PropertyLocationRiskFactor(isPropertyNearARiver));
      DisplayQuote(propertyType, isPropertyNearARiver,
        propertyValue, quoteAmount);
    } // End of QuoteAmount() method
    public static void DisplayQuote(int propertyType,
      string isPropertyNearARiver, double propertyValue,
      double quoteAmount)
    {
      if (isPropertyNearARiver.Equals("Y"))
      {
        isPropertyNearARiver = "Yes";
      }
      else
      {
        isPropertyNearARiver = "No";
      }
      Console.WriteLine("Quote Details");
      Console.WriteLine($"{"Property Type is:", -30} " +
        $"{Enum.GetName(typeof(PropertyTypeEnum),
        propertyType-1), -20}");
      Console.WriteLine($"{"Property Near River:",-30} " +
        $"{isPropertyNearARiver,-20}");
      Console.WriteLine($"{"Property Value is:",-30} " +
        $"{propertyValue,-20}");
      Console.WriteLine();
      Console.WriteLine($"{"Quote amount is:",-30} " +
        $"{quoteAmount,-20}");
    } // End of DisplayQuote() method
  } // End of class PropertyInsurance
} // End of namespace Labs.Chapter20

A window has 14 lines of text. It contains questions and answers regarding the type of property, the closeness to the river, and the estimated value.

Figure 25-38

Lab 2 output

Chapter 21 Labs: Delegates

Lab 1

Write a C# console application that will allow for funds to be added to or withdrawn from a bank account. The application will
  • Have a class called CustomerAccount and inside it
    • Declare a static variable double currentBalance.

    • Declare a method called AddFunds . The method is a value method that returns a value of type double, accepts a value of type double, adds the value passed in to the current balance, and returns the new balance.

    • Define the delegate at the namespace level (this is step 1 of 3):

    public delegate double AmendFundsDelegate(double amount);
  • Have a Main() method that will
    • Instantiate the CustomerAccount class as

    CustomerAccount myCustomer = new CustomerAccount();
    • Instantiate the delegate AmendFundsDelegate amendBalance; and then create the new object, passing it the AddFunds method (this is step 2 of 3):

    amendBalance = new AmendFundsDelegate(myCustomer.AddFunds);
    • Have a variable of type double called transactionAmount, assigning it a value of 100.00.

    • Invoke the delegate, passing it the transactionAmount (this is step 3 of 3).

    • Display the new account balance.

Lab 2

Write a C# console application that will act as a simple calculator to add numbers. The application will
  • Define the delegate at the namespace level (this is step 1 of 3):

public delegate void CalculatorDelegate(int firstNumber, int secondNumber);
  • Have a class called Calculator and inside it
    • Declare a method called Add. The method is a void method that accepts two values of type int and displays the sum of the two values.

    • Declare a method called Subtract. The method is a void method that accepts two values of type int and displays the difference between the two values.

  • Have a class called CalculatorApplication and inside it
    • Have a Main() method that will
      • Instantiate the Calculator class as

    Calculator my Calculator = new Calculator();
    • Instantiate the delegate (this is step 2 of 3):
      CalculatorDelegate myDelegate1 = new CalculatorDelegate(myCalculator.Add);
    • Invoke the delegate, passing it the two required values 8 and 2 (this is step 3 of 3):

    myDelegate1.Invoke(8, 2);

Repeat steps 2 and 3 for the Subtract method, passing in 8 and 2.

Lab 1: Possible Solution with output shown in Figure 25-39

namespace Labs.Chapter21
{
  internal class CustomerAccount
  {
    static double currentBalance;
    /*
    Define the methods we will use. Here we will use one
    non static methods
    */
    public double AddFunds(double amountIn)
    {
      return currentBalance += amountIn;
    } // End of AddFunds() method
    public double WithdrawFunds(double amountOut )
    {
      return currentBalance -= amountOut;
    } // End of WithdrawFunds() method
    /*
    Define the delegates
    We have an access modifier, a return type and the
    parameters of the delegate. This essentially defines the
    methods that can be associated with the delegate, the methods
    must have the same attributes
    A delegate can be declared in the class and therefore
    it is available only to that class's members
    It can be declared in the namespace and therefore it is
    available to all namespace classes and outside the namespace
    */
    /*
    This is step 1. define the delegate, of 3 steps
    */
    public delegate double AmendFundsDelegate(double amount);
    static void Main(string[] args)
    {
      /*
      The steps to use when dealing with delegates are
      1. define the delegate
      2. instantiate the delegate
      3. invoke the delegate
      */
      // Instantiate the CustomerAccount class
      CustomerAccount myCustomer = new CustomerAccount();
      /*
      Instantiate delegate by passing the name of the
      target function as its argument. In this case we will use
      the non static methods so we use the instance name
      This is step 2. instantiate the delegate, of 3 steps
      */
      AmendFundsDelegate amendBalance;
      amendBalance = new AmendFundsDelegate(myCustomer.AddFunds);
      double transactionAmount = 100.00;
      /*
      Now we Invoking The Delegates
      This is step 3. invoke the delegate, of 3 steps
      we could also just use amendBalance(100);
      */
      amendBalance.Invoke(transactionAmount);
      Console.WriteLine($"The new balance is : {currentBalance}");
     // Console.WriteLine(amendBalance.Invoke(transactionAmount + 1000));
    } // End of Main() method
  } // End of class CustomerAccount
} // End of namespace Labs.Chapter21

A window has a line of text that reads as follows, the new balance is, colon, 100.

Figure 25-39

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-40

namespace Labs.Chapter21
{
  /*
  Define the delegates
  We have an access modifier, a return type and the
  parameters of the delegate. This essentially defines the
  methods that can be associated with the delegate, the methods
  must have the same attributes
  This is step 1. define the delegate, of 3 steps
  A delegate can be declared in the class and therefore
  it is available only to that class's members
  It can be declared in the namespace and therefore it is
  available to all namespace classes and outside the namespace
  */
  public delegate void CalculatorDelegate(int firstNumber, int secondNumber);
  internal class Calculator
  {
    /*
    Define the methods we will use. Here we will use one
    non static and one static method
    */
    public void Add(int numberOne, int numberTwo)
    {
      Console.WriteLine($"The total of {numberOne} and {numberTwo}, is {numberOne + numberTwo}");
    }
     public void Subtract(int numberOne, int numberTwo)
    {
      Console.WriteLine($"The difference between {numberOne} and {numberTwo}, is {numberOne - numberTwo}");
    }
  } // End of the class Calculator
  internal class CalculatorApplication
  {
    static void Main(string[] args)
    {
      // Instantiate the Calculator class
      /*
       The steps to use when dealing with delegates are
        1. define the delegate
        2. instantiate the delegate
        3. invoke the delegate
      */
      Calculator myCalculator = new Calculator();
      /*
      Instantiate delegate by passing the name of the
      target function as its argument. In this case we will use
      the non static method so we use the instance name
      This is step 2. instantiate the delegate, of 3 steps
      */
      CalculatorDelegate myDelegate1 = new CalculatorDelegate(myCalculator.Add);
      /*
      Now we Invoking The Delegates
      This is step 3. invoke the delegate, of 3 steps
      we could also just use myAddDelegate(8, 2);
      */
      myDelegate1.Invoke(8, 2);
      /*
      Instantiate delegate by passing the name of the
      target function as its argument. In this case we will use
      the static method so we use the class name not the instance
      This is step 2. instantiate the delegate, of 3 steps
      */
      CalculatorDelegate myDelegate2 = new CalculatorDelegate(myCalculator.Subtract);
      /*
      Now we Invoking The Delegates
      This is step 3. invoke the delegate, of 3 steps
      we could also just use myAddDelegate(8, 2);
      */
      myDelegate2.Invoke(8, 2);
    }
  } // End of the class CalculatorApplication
} // End of namespace Labs.Chapter21

A window has 2 lines of text where the first line reads, the total of 8 and 2, comma, is 10. The second line reads, the difference between 8 and 2, comma, is 6.

Figure 25-40

Lab 2 output

Chapter 22 Labs: Events

Lab 1

Write a C# console application that will allow numbers to be added together, and when the total is greater than a specific value, an event is fired. The application will
  • Have a class called Calculator and inside it
    • Define the delegate:

    public delegate void CalculatorDelegate();
    • Define the event that links to the delegate:

    public event CalculatorDelegate NumberGreaterThanNine;
    • Have an Add() method that
      • Accepts two integers as its parameters.

      • Adds the two numbers and assigns the answer to a variable called answer.

      • Will have a selection construct to check if the answer is greater than 9. If it is, the event NumberGreaterThanNine() is called; otherwise, no action is needed.

      • Display the two numbers and the answer in the console.

  • Have another class called CalculatorApplication, in the same namespace, and inside it
    • Have a Main() method that will
      • Instantiate the Calculator class as

      Calculator myCalculator = new Calculator();
      • Bind the event with the delegate and point to the EventMessage() method:
        myCalculator.numberGreaterThanNine +=
        new Calculator.CalculatorDelegate(EventMessage);
      • Call the Add() method from the Calculator class, passing it the values 8 and 2:

      myCalculator.Add(8,2);
      Outside the Main() method but inside the CalculatorApplication class
      • Create the EventMessage() method so that it outputs a message:
        static void EventMessage()
        {
        Console.WriteLine("*Number greater than 9  detected*");
        }

Lab 2

Write a C# console application that will check if any repair claim amounts are greater than a value of 5000, displaying a message if they are. The application will
  • Have a class called RepairClaimCheckerLogic and inside it
    • Define the delegate:
      public delegate void RepairClaimCheckerDelegate(int claimNumber, double claimValue);
    • Define the event that links to the delegate:
      public event RepairClaimCheckerDelegate OverLimit;
    • Declare and create an array to hold three values of data type double:

    double[] repairClaimsAmounts = new double[3];
    • Have a GetRepairClaimData() method that
      • Accepts no parameters

      • Will have an iteration construct to iterate three times and ask the user to input the repair claim amount, storing each input value in the array of doubles

    • Have a ReadAndCheckRepairClaims() method that
      • Accepts no parameters

      • Will have an iteration construct to iterate three times and read the repair claim amount from the array of doubles and check if the value is greater than 5000. If the value is greater than 5000, then the overLimit event is called, passing it the position of the value in the array and the value that is exceeding the 5000 limit.

  • Have another class called RepairClaimChecker, in the same namespace, and inside it
    • Have a Main() method that will
      • Instantiate the RepairClaimCheckerLogic class as
        RepairClaimCheckerLogic myRepairClaimCheckerLogic = new RepairClaimCheckerLogic();
      • Call the GetRepairClaimData() method from the RepairClaimCheckerLogic class:

    myRepairClaimCheckerLogic.GetRepairClaimData();
    • Bind the event with the delegate and point to the OverLimitMessage() method:
      myRepairClaimCheckerLogic.overLimit
      += new RepairClaimCheckerLogic.RepairClaimCheckerDelegate(OverLimitMessage);

      Outside the Main() method but inside the RepairClaimChecker class, create the OverLimitMessage() method so that it outputs a message:

      static void OverLimitMessage(int claimNumber, double value)
      {
      Console.WriteLine($"*** Claim {claimNumber} for {value} needs to be verified***");
      }
    • Call the ReadAndCheckRepairClaims () method from the RepairClaimCheckerLogic class:

    myRepairClaimCheckerLogic.ReadAndCheckRepairClaims();

Lab 1: Possible Solution with output shown in Figure 25-41

namespace Labs.Chapter22
{
  // Subscriber class
  public class CalculatorApplication
  {
    static void Main(string[] args)
    {
      Calculator myCalculator = new Calculator();
      /*
      Event is bound with the delegate
      Here we are creating a delegate, a pointer, to the method
      called EventMessage and adding it to the list of
      Event Handlers
      */
      myCalculator.NumberGreaterThanNine +=
        new Calculator.CalculatorDelegate(EventMessage);
      // Call the Add method in the Calculator class
      myCalculator.Add(8,2);
    }
    /*
    Delegates call this method when the event is raised.
    This is the code that executes when NumberGreaterThanNine
    is fired
    */
    static void EventMessage()
    {
      Console.WriteLine("* Number greater than 9 detected *");
    }
  } // End of the class CalculatorApplication
  // Publisher class
  public class Calculator
  {
    /*
    Declare the delegate. This delegate can be used to point to
    any method which is a void method and accepts no parameters
    */
    public delegate void CalculatorDelegate();
    /*
    Declare the event. This event can cause any method that
    matches the CalculatorDelegate to be called
    */
    public event CalculatorDelegate NumberGreaterThanNine;
    public void Add(int numberOne, int numberTwo)
    {
      int answer = numberOne + numberTwo;
      if(answer > 9)
      {
        /*
        Here we are raising the event and this event is linked
        to the method called EventMessage() which accepts
        no values and displays a message
        */
        NumberGreaterThanNine(); // Raised event
      }
      Console.WriteLine($"The total of {numberOne} and {numberTwo}, is {numberOne + numberTwo} ");
    }
  } // End of the class Calculator
} // End of namespace Labs.Chapter22

A window has 2 lines of text. The first line reads, asterisk symbol, number greater than 9 detected, asterisk symbol.

Figure 25-41

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-42

namespace Labs.Chapter22
{
  /*
  A DELEGATE is a type which defines a method signature and
  holds a reference for a method whose signature will match the
  delegate. Therefore delegates are used to reference a method.
  An EVENT is a 'notification' which is raised by an object
  to signify the occurrence of some action. Our delegate is then
  associated with the event and holds a reference to a
  method which will be called when the event is raised.
  An event is associated with an Event Handler using a Delegate.
  When the Event is raised it sends a signal to delegates
  and the delegate executes the correct matching function.
  The steps to use events are:
  1: Define the Delegate
  2: Define the Event with same the same name as the Delegate.
  3: Define the Event Handler that responds when event is raised.
  */
  // Subscriber class
  public class RepairClaimChecker
  {
    static void Main(string[] args)
    {
      RepairClaimCheckerLogic myRepairClaimCheckerLogic =
        new RepairClaimCheckerLogic();
      myRepairClaimCheckerLogic.GetRepairClaimData();
      /*
      Event is bound with the delegate
      Here we are creating a delegate, a pointer, to the method
      called OverLimitMessage and adding it to the list of
      Event Handlers
      */
      myRepairClaimCheckerLogic.OverLimit
        += new RepairClaimCheckerLogic.RepairClaimCheckerDelegate(OverLimitMessage);
      myRepairClaimCheckerLogic.ReadAndCheckRepairClaims();
    }
    /*
    Delegates call this method when the event is raised.
    This is the code that executes when OverLimit is fired
    */
    static void OverLimitMessage(int claimNumber, double value)
    {
      Console.WriteLine($"*** Claim {claimNumber} for {value} needs to be verified***");
    }
  } // End of the class RepairClaimChecker
  // Publisher class
  public class RepairClaimCheckerLogic
  {
    /*
    Declare the delegate. This delegate can be used to point
    to any method which is a void method and accepts an int
    followed by a double as its parameters
    */
    public delegate void RepairClaimCheckerDelegate(int claimNumber, double claimValue);
    /*
    Declare the event. This event can cause any method that
    matches the RepairClaimCheckerDelegate to be called
    */
    public event RepairClaimCheckerDelegate OverLimit;
    double[] repairClaimsAmounts = new double[3];
    public void GetRepairClaimData()
    {
      for (int i = 0; i < 3; i++)
      {
        Console.WriteLine("What is the repair claim amount?");
        double claimAmount = Convert.ToDouble(Console.ReadLine());
        repairClaimsAmounts[i] = claimAmount;
      } // End of the for iteration construct
    } // End of GetRepairClaimData() method
    public void ReadAndCheckRepairClaims()
    {
      for (int i = 0; i < 3; i++)
      {
        if (repairClaimsAmounts[i] > 5000)
        {
          /*
          Here we are raising the event and this event is linked
          to the method called  OverLimitMessage() which accepts
          the two values and displays a message
          */
          OverLimit(i, repairClaimsAmounts[i]); // Raised event
        } // End of the if selection construct
      } // End of the for iteration construct
    } // End of the ReadAndCheckRepairClaims() method
  } // End of the class RepairClaimCheckerLogic
} // End of namespace Labs.Chapter22

A window has 8 lines of text which include the questions about what the repair claim amount is. The last 2 lines indicate that claims have to be verified.

Figure 25-42

Lab 2 output

Chapter 23 Labs: Generics

Lab 1

Write a C# console application that will use a generic class and method , allowing any two value types to be passed to the method, which will add the two values and return the answer. The values can therefore be int, float, double, string, etc. The application will
  • Have a class called Calculator, which accepts any type. It is generic <T> and this class will
    • Have a method called AddTwoValues() , which has two parameters. The first parameter is called valueOne of type T and the second parameter is called valueTwo of type T, and inside the method
      • There is a variable called firstValue, which is of data type dynamic, and it is assigned to valueOne.

      • There is a variable called secondValue, which is of data type dynamic, and it is assigned to valueTwo.

      • The answer variable is assigned the “sum” of firstValue and secondValue (firstValue + secondValue).

      The method is a value method and it returns the variable answer.

  • Have a class called CalculatorApplicaton and inside it
    • A Main() method that
      • Instantiates the Calculator class with type <int>, naming the instantiation intCalculator

      • Then calls the AddTwoValues() method, passing it the values 80 and 20, and writes the returned value to the console

      • Instantiates the Calculator class with type <string>, naming the instantiation stringCalculator

      • Then calls the AddTwoValues() method, passing it the values “Gerry” and “Byrne”, and writes the returned value to the console

      Repeat the instantiation and method call for float and double data types.

Lab 2

Write a C# console application that will use a generic method, allowing any value type to be passed to it, and on identification of the type, a Boolean true or false will be returned. The application will use claim values and policy ids, which will be passed to the method where the total of the claims will be calculated. The application will
  • Have a class called ClaimLogic and inside it
    • There will be a method to create an ArrayList with the following values:
      "POL1234", 2000.99, "POL1235", 3000.01, "POL1236", 599.99, "POL1237", 399.01, "POL1238", 9000, "POL1239"

      Then this ArrayList is passed to the next method.

    • A method is created that accepts the ArrayList and iterates the values, and for each value it passes the value to another method that is generic and accepts any value type. The generic method then returns true if the value passed to it is an int or a double and false if it is any other type.

    • When the value returned to the iteration is Boolean true, add the value to an accumulated total of the claims, and increment a number of valid claims variable by 1.

    • When the value returned to the iteration is Boolean false, increment a number of policy ids variable by 1.

    • Finally, display the total of the claims, the number of claims, and the number of policy ids.

  • Have a class called CompareClaims and inside it
    • Have a Main() method that calls the method that creates the ArrayList.

Lab 1: Possible Solution with output shown in Figure 25-43

using System;
namespace Labs.Chapter23
{
  internal class CalculatorApplication
  {
    static void Main(string[] args)
    {
      Calculator<int> intCalculator = new Calculator<int>();
      Console.WriteLine($"Using integers: {intCalculator.AddTwoValues(80, 20)}");
      Calculator<string> stringCalculator = new Calculator<string>();
      Console.WriteLine($"Using strings: {stringCalculator.AddTwoValues("Gerry", "Byrne")}");
      Calculator<float> floatCalculator = new Calculator<float>();
      Console.WriteLine($"Using floats: {floatCalculator.AddTwoValues(3.5F, 100.0F)}");
      Calculator<double> doubleCalculator = new Calculator<double>();
      Console.WriteLine($"Using doubles: {doubleCalculator.AddTwoValues(8.99, 1.02)}");
    } // End of Main() method
  } // End of CalculatorApplication class
  // Create a generic class
  public class Calculator<T>
  {
    public T AddTwoValues(T valueOne, T valueTwo)
    {
      /*
      In C# we have a dynamic type which is used avoid
      compile-time type checking of the variable.
      Instead the compiler gets the type at the run time and
      this suits this example well as we are using generic types.
      */
      dynamic firstValue = valueOne;
      dynamic secondValue = valueTwo;
      return firstValue + secondValue;
    } //End of AddTwoValues() method
  } // End of Calculator class
} // End of namespace Labs.Chapter23

A window has 4 lines of text. The text mention using integers, strings, floats, and doubles, as well as their corresponding values.

Figure 25-43

Lab 1 output

Lab 2: Possible Solution with output shown in Figure 25-44

using System.Collections;
namespace Labs.Chapter23
{
  internal class CompareClaims
  {
    static void Main(string[] args)
    {
      ClaimLogic myCalculatorLogic = new ClaimLogic();
      myCalculatorLogic.CreateArrayListOfValues();
    } // End of Main() method
  } // End of Calculator class
  public class ClaimLogic
  {
    public void CreateArrayListOfValues()
    {
      ArrayList repairClaimsAmounts = new ArrayList();
      repairClaimsAmounts.Add("POL1234");
      repairClaimsAmounts.Add(2000.99);
      repairClaimsAmounts.Add("POL1235");
      repairClaimsAmounts.Add(3000.01);
      repairClaimsAmounts.Add("POL1236");
      repairClaimsAmounts.Add(599.99);
      repairClaimsAmounts.Add("POL1237");
      repairClaimsAmounts.Add(399.01);
      repairClaimsAmounts.Add("POL1238");
      repairClaimsAmounts.Add(9000);
      repairClaimsAmounts.Add("POL1239");
      ValidateAndTotal(repairClaimsAmounts);
    }
    private void ValidateAndTotal(ArrayList repairClaimsAmounts)
    {
      double totalOfClaims = 0.00;
      int validClaims = 0, policyIds =0;
      for (int i = 0; i < repairClaimsAmounts.Count; i++)
      {
        if (Calculate(repairClaimsAmounts[i]))
        {
          totalOfClaims += Convert.ToDouble(repairClaimsAmounts[i]);
          validClaims++;
        } // End of the if selection construct
        else
        {
          policyIds++;
        }
      } // End of the for iteration construct
      Console.WriteLine($"There were {validClaims} claims");
      Console.WriteLine($"Claims total is {totalOfClaims}");
      Console.WriteLine($"There were {policyIds} policies");
    } // End of ValidateAndTotal() method
    //Now this method can accept any data type
    public static bool Calculate<T>(T value)
    {
      switch (value)
      {
        case int i:
          return true;
        case double d:
          return true;
        default:
          return false;
      }
    } // End of Calculate() method
  } // End of CalculatorLogic class
} // End of namespace Labs.Chapter23

A window has 3 lines of text where line 1 reads, there were 5 claims. Lines 2 and 3 indicate the total claims amount and the number of policies.

Figure 25-44

Lab 2 output

Chapter Summary

Well, that was a lot of coding, and hopefully we tried to use our own learnings and code style rather than just looking at the basic solutions given for the labs.

As we finish this penultimate chapter, we can say we have achieved so much. We should be immensely proud of the learning to date. We are getting so close to our target we can almost touch it, but we have just one more small step to take.

An illustration of concentric circles with a text below that reads, our target is getting closer. The two circles at the center are shaded in green.

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

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