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

7. Casting and Parsing

Gerard Byrne1  
(1)
Belfast, Ireland
 

Data Types, Casting, and Parsing

We learned in Chapter 6 that we can declare variables with a data type and then assign values to them in our code. We learned that we can accept user input and assign the input value to a variable, and we saw that there are times when we will need to convert a variable from one data type to another. In this context we learned about narrowing and widening conversions, and we used a conversion from an int to a byte, which involved casting, for example, (byte).

In C#, casting is a method used to convert one data type to another. Casting is used as an explicit conversion and tells the compiler what to do, but we need to be aware that there may be a loss of data. So we use casting to achieve a numeric conversion where the destination data type we are assigning the value to is of a lesser precision. Casting is a conversion from one numeric data type to another numeric data type as discussed earlier with narrowing and widening.

If we think back to what we have read about the numeric data types, we will see that we start with a less precise data type, sbyte, and we move up to the most precise ulong data type as shown in Table 7-1.
Table 7-1

Integral types

Integral types

byte

Byte

1

May contain integers from 0 to 255

sbyte

SByte

1

Signed byte from –128 to 127

short

Int16

2

Ranges from –32,768 to 32,767

ushort

UInt16

2

Unsigned, ranges from 0 to 65,535

int

Int32

4

Ranges from –2,147,483,648 to 2,147,483,647

uint

UInt32

4

Unsigned, ranges from 0 to 4,294,967,295

long

Int64

8

Ranges from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulong

UInt64

8

Unsigned, ranges from 0 to 18,446,744,073,709,551,615

So taking a data type in Table 7-1 and trying to assign it to a variable with a data type above it in the table means we are moving to a less precise format and therefore we must use a cast, casting. Now we will code an example of int to short.

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

    Right-click the solution CoreCSharp .

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose New Project, as shown in Figure 7-1.

     

A window depicts a tab for chapter 4 dot c s p r o j. On the right is another window for solution explorer and 2 context windows in which the options add and new project are highlighted.

Figure 7-1

Adding a new C# project

  1. 4.

    Choose Console App from the listed templates as shown in Figure 7-2.

     

A window titled console app. The description reads, a project for creating a command-line application that can run on dot net on Windows, Linux, and Mac O S. Below the description are buttons for C hash, Linux, Mac O S, Windows, and Console.

Figure 7-2

Selecting a new C# console project

  1. 5.

    Click the Next button.

     
  2. 6.

    Name the project Chapter7, leaving it in the same location, as shown in Figure 7-3.

     

A dialog box titled configure your new project. Console app is selected from the menu bar. Below the menu bar is an input box for the project name and a dropdown menu for location.

Figure 7-3

Naming a new C# console project

  1. 7.

    Click the Next button.

     
  2. 8.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher, as shown in Figure 7-4.

     

A dropdown menu for framework from which the option dot net 6.0 long term support is selected.

Figure 7-4

Choosing the project framework

  1. 9.

    Click the Create button.

     
The Chapter7 project will appear in the solution, as shown in Figure 7-5.

A window for solution explorer depicts a tree list for solution core c sharp with 4 projects labeled as chapters 4 to 7 listed.

Figure 7-5

Solution Explorer displaying all projects

  1. 10.

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

     
  2. 11.

    Click the Set as Startup Project option.

     
Figure 7-6 shows that the Chapter7 project name has been made to have bold text, indicating that it is the new startup project and that it is the Program.cs file within it that will be executed when we run the debugging.

A window of a tree list with chapter 7 highlighted and expanded. Below this are elements labeled dependencies and program dot c s.

Figure 7-6

Solution Explorer displaying the startup project

We will now copy the code from the Program.cs file in Chapter6 to the Program.cs file in Chapter7.
  1. 1.

    Double-click the Program.cs file in the Chapter6 project.

     
  2. 2.

    Highlight ALL the code within the program, yes, including the namespace and Main method.

     
  3. 3.

    Choose Copy.

     
  4. 4.

    Double-click the Program.cs file in the Chapter7 folder.

     
  5. 5.

    Highlight the existing code and delete it.

     
  6. 6.

    Right-click inside the blank editor window.

     
  7. 7.

    Choose Paste.

     
Now, the namespace is called Chapter6 so we will rename it as Chapter7. We have a choice of ways to rename the namespace to Chapter7, but we will select the same one as we did in the last chapter.
  1. 1.

    Right-click the word Chapter6, as shown in Figure 7-7.

     
  2. 2.

    Choose Quick Actions and Refactorings, as shown in Figure 7-7.

     

A pop-up window displays the option for quick actions and refactorings that is selected.

Figure 7-7

Renaming the namespace using Quick Actions and Refactorings

  1. 3.

    Click the Change namespace to Chapter7 option, as shown in Figure 7-8.

     
  2. 4.

    Press the Enter key.

     

A context menu in which the option to change namespace to chapter 7 is selected. On the right are lines that read, lines 20 to 22, namespace chapter 6, newline, namespace chapter 7.

Figure 7-8

Renaming the namespace to match the project name

The namespace will now have been renamed to Chapter7.

We will amend the code by adding two new variables, one of data type int and called maximumAmountForRepairCosts and the other of data type short and called maximumAmountForCarHire.
  1. 1.

    Amend the code to add the two variables, as in Listing 7-1.

     
    int vehicleCurrentMileage;
    DateTime dateOfBirthOfMainDriver;
    // max value of int is 2,147,483,647
    int maximumAmountForRepairCosts = 32767;
    // max value of short is 32,767
    short maximumAmountForCarHire = 0;
Listing 7-1

Two variables of types int and short with initial values

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  • We will now assign the value of the maximumAmountForRepairCosts variable to the variable called maximumAmountForCarHire.

  1. 4.

    Amend the code, as in Listing 7-2.

     
      Console.WriteLine("You have told us that the main " +
        "driver was born on "
        + dateOfBirthOfMainDriver.ToShortDateString());
      /*
      Now we are trying to put the int variable
      maximumAmountForRepairCosts into the short variable
      maximumAmountForCarHire but this is not possible without
      something being changed.
      This is where the cast comes into play.
      */
      maximumAmountForCarHire = maximumAmountForRepairCosts;
    } // End of Main() method
  } // End of Program class
} // End of Chapter7 namespace
Listing 7-2

Assign one variable value to another variable

  1. 5.

    Amend the code, as in Listing 7-3, to display the values of maximumAmountForRepairCosts and maximumAmountForCarHire.

     
    maximumAmountForCarHire = maximumAmountForRepairCosts;
      Console.WriteLine("The int variable " +
        "maximumAmountForRepairCosts has a value of "
        + maximumAmountForRepairCosts);
      Console.WriteLine();
      Console.WriteLine("The short variable " +
        "maximumAmountForCarHire has a value of "
        + maximumAmountForCarHire);
    } // End of Main() method
  } // End of Program class
} // End of Chapter7 namespace
Listing 7-3

Display messages including the variables

  • As we see in Figure 7-9, the variable called maximumAmountForRepairCosts within the assignment statement is underlined with red. So we need to fix this issue, once we understand what is causing the error.

  1. 6.

    Hover over the red underline and read the pop-up message, as in Figure 7-9.

     

A pop-up window depicts an error that reads C S 0266, cannot implicitly convert type int to short, an explicit conversion exists. Are you missing a cast, question mark, show potential fixes, alt plus enter or control plus inside parentheses.

Figure 7-9

Hovering over the error to see the help message

In the error message , we are being told that maximumAmountForRepairCosts cannot be implicitly converted from an int data type to a short data type. Even though the error message does not specifically say it, the cause of the error is that we are trying to perform a narrowing conversion, and this cannot be done implicitly. We must perform the conversion with an explicit conversion, a cast in this case. If we look carefully, we will see that we are asked the question: "are you missing a cast?" This means that we can perform the conversion using a cast and we will be casting the maximumAmountForRepairCosts variable, which is of data type int, so it fits into a data type short.
  1. 7.

    Amend the code, as in Listing 7-4, to perform the casting.

     
    maximumAmountForCarHire = (short)maximumAmountForRepairCosts;
    Console.WriteLine("The int variable " +
      "maximumAmountForRepairCosts has a value of "
      + maximumAmountForRepairCosts);
Listing 7-4

Cast int type to short type

Now we should see that the red underline error has disappeared. We have fixed the conversion issue by using a cast to make the value of the variable of data type int into a short value.

Now, running this application with the int variable being set to have its maximum value of 32767 will be fine. This means the casting will take place without loss of accuracy, on this occasion.
  1. 8.

    Click the File menu.

     
  2. 9.

    Choose Save All.

     
  3. 10.

    Click the Debug menu.

     
  4. 11.

    Choose Start Without Debugging.

     
  5. 12.

    Type Ford as the manufacturer name.

     
  6. 13.

    Press the Enter key on the keyboard.

     
  7. 14.

    Type Fiesta as the model name.

     
  8. 15.

    Press the Enter key on the keyboard.

     
  9. 16.

    Type Blue as the vehicle color.

     
  10. 17.

    Press the Enter key on the keyboard.

     
  11. 18.

    Type 5 as the vehicle age.

     
  12. 19.

    Press the Enter key on the keyboard.

     
  13. 20.

    Type 6999.99 as the estimated vehicle value.

     
  14. 21.

    Press the Enter key on the keyboard.

     
  15. 22.

    Type 50000 as the number of kilometers on the odometer of the vehicle.

     
  16. 23.

    Press the Enter key on the keyboard.

     
  17. 24.

    Type 1998-01-01 as the date of birth for the main driver of the vehicle.

     
  18. 25.

    Press the Enter key on the keyboard.

     
Figure 7-10 shows the console window and we can see that the casting has worked.

A series of text on a console window illustrates that casting is successful.

Figure 7-10

Casting int type to short type

  1. 26.

    Press the Enter key to close the console window.

     

If we amend the code so that the int variable is set to have a value that is one more than the maximum value of the short data type, 32768, there will be an issue. This means the casting will take place with loss of accuracy.

We will now change the value of the int variable so that it is one more than the maximum value of a short data type. This will mean that when we cast the int variable, it will be too large for the variable maximumAmountForCarHire, data type short, to hold.
  1. 27.

    Amend the code as in Listing 7-5.

     
    DateTime dateOfBirthOfMainDriver;
    // max value of int is 2,147,483,647
    int maximumAmountForRepairCosts = 32768;
    // max value of short is 32,767
    short maximumAmountForCarHire = 0;
Listing 7-5

Assign a value of 32768 to a short – this is outside the type range

  1. 28.

    Click the File menu.

     
  2. 29.

    Choose Save All.

     
  3. 30.

    Click the Debug menu.

     
  4. 31.

    Choose Start Without Debugging.

     
  5. 32.

    Click in the console window.

     
  6. 33.

    Type Ford as the manufacturer name.

     
  7. 34.

    Press the Enter key on the keyboard.

     
  8. 35.

    Type Fiesta as the model name.

     
  9. 36.

    Press the Enter key on the keyboard.

     
  10. 37.

    Type Blue as the vehicle color.

     
  11. 38.

    Press the Enter key on the keyboard.

     
  12. 39.

    Type 5 as the vehicle age.

     
  13. 40.

    Press the Enter key on the keyboard.

     
  14. 41.

    Type 6999.99 as the estimated vehicle value.

     
  15. 42.

    Press the Enter key on the keyboard.

     
  16. 43.

    Type 50000 as the number of kilometers on the odometer of the vehicle.

     
  17. 44.

    Press the Enter key on the keyboard.

     
  18. 45.

    Type 1998-01-01 as the date of birth for the main driver of the vehicle.

     
  19. 46.

    Press the Enter key on the keyboard.

     
We can now see that there is an output, as shown in Figure 7-11. There has not been a compile error , but the result is not correct.

A series of text on a console window. A line reads, the short variable maximum amount for car hire has a value of negative 32768. A cloud bubble that points toward this line asks if the casting is successful.

Figure 7-11

Casting appears to have worked successfully

  1. 47.

    Change the value back to 32767 from 32768.

     

Amend the code to use a Boolean data type and use parsing for the conversion.

We will now amend the code to ask the user to input True or False at the console. Remember that the console input will be a string. We will then assign the console input to a variable of data type bool .
  1. 1.

    Amend the code, as in Listing 7-6, to add two new variables, one of data type string and the other of data type bool (Boolean).

     
    // max value of short is 32,767
    short maximumAmountForCarHire = 0;
    bool fullyComprehensiveRequirement = true;
Listing 7-6

Add variables of types string and bool

  1. 2.

    Amend the code, as in Listing 7-7, to ask the user for input.

     
      Console.WriteLine("You have told us that the main " +
        "driver was born on " + dateOfBirthOfMainDriver);
      Console.WriteLine("You have told us that the main " +
        "driver was born on "
        + dateOfBirthOfMainDriver.ToShortDateString());
      Console.WriteLine("Do we require fully comprehensive" +
        " insurance (enter the word True or False)? ");
Listing 7-7

Ask for user input

  1. 3.

    Amend the code, as in Listing 7-8, to assign the value entered at the console to the variable fullyComprehensiveRequirement.

     
      Console.WriteLine("You have told us that the main " +
        "driver was born on "
        + dateOfBirthOfMainDriver.ToShortDateString());
      Console.WriteLine("Do we require fully comprehensive" +
        " insurance (enter the word True or False)? ");
      fullyComprehensiveRequirement = Console.ReadLine();
Listing 7-8

Read the string input and assign it to a variable

  1. 4.

    Amend the code, as in Listing 7-9, to display the value of the variable fullyComprehensiveRequirement, which is of data type bool.

     
      Console.WriteLine("Do we require fully comprehensive" +
        " insurance (enter the word True or False)? ");
      fullyComprehensiveRequirement = Console.ReadLine();
      Console.WriteLine("It is " + fullyComprehensiveRequirement
        + " that we require fully comprehensive insurance");
Listing 7-9

Display the bool value

As shown in Figure 7-12, there is a red underline under the statement Console.ReadLine(). So we need to fix the issue once we understand what is causing the error.

A series of text on a console window depicts a conversion error message, cannot implicitly convert type string to bool. It points to a code line that assigns the value of console dot read line open and close parenthesis to the variable named fully comprehensive requirement.

Figure 7-12

Hovering over the error to see the help message

Hovering over the word Console, we will be presented with an error message. We could also hover over the ReadLine() part of the statement and we will get a similar message. We are being told that fullyComprehensiveRequirement cannot be implicitly converted from a string data type to a bool data type. We need to fix the issue by performing a conversion as the message says. There is no talking about a cast as we saw in the previous example because this is not a conversion from one numeric data type to another numeric data type.

We can use the Parse() method , as discussed earlier. The Parse() method will be the Boolean.Parse() method, which accepts a string value and “converts,” parses, it to a Boolean.
  1. 5.

    Amend the code, as in Listing 7-10, to perform the parsing.

     
      Console.WriteLine("Do we require fully comprehensive" +
        " insurance (enter the word True or False)? ");
      fullyComprehensiveRequirement =
        Boolean.Parse(Console.ReadLine());
      Console.WriteLine("It is " + fullyComprehensiveRequirement
        + " that we require fully comprehensive insurance");
Listing 7-10

Parse the string input to a bool

  • Now we should see that the red underline error has disappeared as we fixed the conversion issue .

  1. 6.

    Click the File menu.

     
  2. 7.

    Choose Save All.

     
  3. 8.

    Click the Debug menu.

     
  4. 9.

    Choose Start Without Debugging.

     
  5. 10.

    Click in the console window.

     
  6. 11.

    Type Ford as the manufacturer name.

     
  7. 12.

    Press the Enter key on the keyboard.

     
  8. 13.

    Type Fiesta as the model name.

     
  9. 14.

    Press the Enter key on the keyboard.

     
  10. 15.

    Type Blue as the vehicle color.

     
  11. 16.

    Press the Enter key on the keyboard.

     
  12. 17.

    Type 5 as the vehicle age.

     
  13. 18.

    Press the Enter key on the keyboard.

     
  14. 19.

    Type 6999.99 as the estimated vehicle value.

     
  15. 20.

    Press the Enter key on the keyboard.

     
  16. 21.

    Type 50000 as the number of kilometers on the odometer of the vehicle.

     
  17. 22.

    Press the Enter key on the keyboard.

     
  18. 23.

    Type 1998-01-01 as the date of birth for the main driver of the vehicle.

     
  19. 24.

    Press the Enter key on the keyboard.

     
  20. 25.

    Type True for the answer to the question. It is true that we require fully comprehensive insurance.

     
The output will be as shown in Figure 7-13.

A series of text on a console window. A cloud bubble that reads, Boolean used, points to a text that reads, true.

Figure 7-13

Boolean type as input

We might also think of a Convert.ToBoolean() method to do the conversion, as in Listing 7-11. Yes, that would work.
      fullyComprehensiveRequirement =
        Boolean.Parse(Console.ReadLine());
      fullyComprehensiveRequirement =
        Convert.ToBoolean(Console.ReadLine());
      Console.WriteLine("It is " + fullyComprehensiveRequirement
        + " that you require fully comprehensive insurance");
Listing 7-11

Using the Convert class ToBoolean() method to parse

We can therefore use
      fullyComprehensiveRequirement =
        Boolean.Parse(Console.ReadLine());
or
      fullyComprehensiveRequirement =
        Convert.ToBoolean(Console.ReadLine());

Chapter Summary

In this chapter we have learned about the particularly important programming concepts of parsing and casting and have seen the “subtle” difference between them. We have seen that in parsing we use the wrapper class that represents the data type, for example, Boolean, and we noted that this class, like all classes, starts with a capital letter. Each wrapper class has methods that will perform the parsing, for example, Parse(), and the method will be passed the name of the variable to be parsed, converted.

We are making really great progress, and we should keep it foremost in our programming thoughts that data types, casting, parsing, and conversions are a core programming concept and will be used throughout the chapters in this book, but more importantly, they are widely used in commercial applications.

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

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

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

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