# Convert data types using casting and conversion techniques
Take control of the data in your applications, knowing when to apply the
correct technique to change data types as needed.
### Learning objectives
Use the casting operator to cast a value into a different data type.
Use conversion methods to convert a value into a different data type.
Guard against the loss of data when performing a cast or conversion operation.
Use the `TryParse()` method to safely convert a string into a numeric data type.
## Introduction
Suppose you're a software developer on a team working on medical intake form
automation. You're tasked with delivery of the application features for
collecting data entered by a medical technician before the doctor sees the
patient. The technician can use the application to record the date and time,
patient age, height, weight, pulse, and blood pressure. The application also
provides text fields for other information, such as the reason for the visit,
current prescriptions, and other items. You work with many data that is in a
mix of data types. For the prototype, you'll build a console application and
collect all of the input as `strings`.
Because the input is initially input as a string, you need to occasionally
change values from one data type into another in the code. A simple example is
any mathematical operation you want to perform with string data. You would
first need to change the value into a numeric data type, like `int`, and then you
could manipulate the operation. Alternatively, you may want to format and
output a numeric value for a summary report using string interpolation.
You use different techniques to change a data type when necessary. You learn
when to use one technique over another, and when a given technique might risk
the loss of data.
By the end of this module, you're able to take control of the data in your
applications, knowing when to apply the correct technique to change data types
as needed.
### Learning objectives
In this module, you'll:
- Use the casting operator to cast a value into a different data type.
- Use conversion methods to convert a value into a different data type.
- Guard against the loss of data when performing a cast or conversion operation.
- Use the `TryParse()` method to safely convert a string into a numeric data
type.
---
## Exercise
### Explore data type casting and conversion
There are multiple techniques to perform a data type conversion. The technique
you choose depends on your answer to two important questions:
- Is it possible, depending on the value, that attempting to change the value's data type would throw an exception at run time?
- Is it possible, depending on the value, that attempting to change the value's data type would result in a loss of information?
In this exercise, you work your way through these questions, the implications of their answers, and which technique you should use when you need to change the data type.
#### Prepare your coding environment
Create a new console application. At the Terminal command prompt type:
`dotnet new console -o ./path_to/Project` or `dotnet new console -n "Project"`
and then press Enter.
This .NET CLI command uses a .NET program template to create a new C# console
application project in the specified folder location.
You use this C# console project to create, build, and run code samples during
this module.
Close the Terminal panel.
### Question
**Is it possible that attempting to change the value's data type would throw an
exception at run time?**
The C# compiler attempts to accommodate your code, but doesn't compile
operations that could result in an exception. When you understand the C#
compiler's primary concern, understanding why it functions a certain way is
easier.
#### Write code that attempts to add an `int` and a `string` and save the result in an `int`
Type the following code into the Visual Studio Code Editor:
```cs
int first = 2;
string second = "4";
int result = first + second;
Console.WriteLine(result);
```
Here, you're attempting to add the values `2` and `4`. The value `4` is of type
`string`. Will this work?
At the Terminal command prompt, to run your code, type `dotnet run` and then
press Enter.
You should see the following approximate output
Windows:
```txt
C:\Users\someuser\Documents\csharpprojects\TestProject\Program.cs(3,14): error CS0029: Cannot implicitly convert type 'string' to 'int'
```
Linux:
```txt
/home/user/Projects/TestProject/Program.cs(3,14): error CS0029: Cannot implicitly convert type 'string' to 'int'
```
> Note
> If you see a message saying "Couldn't find a project to run", ensure that the
Terminal command prompt displays the expected TestProject folder location. For
Create a looping structure that can be used to iterate through each string
value in the array `values`.
Complete the required code, placing it within the array looping structure code
block. It's necessary to implement the following business rules in your code
logic:
- Rule 1: If the value is alphabetical, concatenate it to form a message.
- Rule 2: If the value is numeric, add it to the total.
- Rule 3: The result should match the following output:
```txt
Message: ABCDEF
Total: 68.3
```
The Program.cs file must be saved before building or running the code.
At the Terminal command prompt, to run your code, type `dotnet run` and then
press Enter.
You should see the following output:
```txt
Message: ABCDEF
Total: 68.3
```
> Note
> If you see a message saying "Couldn't find a project to run", ensure that the Terminal command prompt displays the expected TestProject folder location. For example: C:\Users\someuser\Desktop\csharpprojects\TestProject>
Whether you get stuck and need to peek at the solution or you finish
successfully, continue to view a solution to this challenge.
---
## Exercise
### Complete a challenge to output math operations as specific number types
Here's a second chance to use what you've learned about casting and conversion
to solve a coding challenge.
The following challenge helps you to understand the implications of casting
values considering the impact of narrowing and widening conversions.
Delete or comment out all of the code from the earlier exercise
Enter the following "starter" code:
```cs
int value1 = 11;
decimal value2 = 6.2m;
float value3 = 4.3f;
// Your code here to set result1
// Hint: You need to round the result to nearest integer (don't just truncate)
Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");
// Your code here to set result2
Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");
// Your code here to set result3
Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");
```
Replace the code comments in the starter code with your own code to solve the
challenge:
- Solve for `result1`: Divide `value1` by `value2`, display the result as an
`int`
- Solve for `result2`: Divide `value2` by `value3`, display the result as a
`decimal`
- Solve for `result3`: Divide `value3` by `value1`, display the result as a
`float`
Solve the challenge so that your output resembles:
```txt
Divide value1 by value2, display the result as an int: 2
Divide value2 by value3, display the result as a decimal: 1.4418604651162790697674418605
Divide value3 by value1, display the result as a float: 0.3909091
```
The Program.cs file must be saved before building or running the code.
At the Terminal command prompt, to run your code, type `dotnet run` and then
press Enter.
You should see the following output:
```txt
Divide value1 by value2, display the result as an int: 2
Divide value2 by value3, display the result as a decimal: 1.4418604651162790697674418605
Divide value3 by value1, display the result as a float: 0.3909091
```
---
## Summary
Your goal was to use several different techniques to change the data type of a
given value.
You used *implicit conversion*, relying on the C# compiler to perform *widening
conversions*. When the compiler was unable to perform an implicit conversion,
you used explicit conversions. You used the `ToString()` method to explicitly
convert a numeric data type into a `string`.
When you needed to perform `narrowing conversions`, you used several different
techniques. You used the casting operator `()` when the conversion could be
made safely and were willing to accept truncation of values after the decimal.
And you used the `Convert()` method when you wanted to perform a conversion and
use common rounding rules when performing a narrowing conversion.
Finally, you used the `TryParse()` methods when the conversion from a `string`
to a numeric data type could potentially result in a data type conversion
exception.
Without this wealth of options, it would be difficult to work in a typed
programming language. Fortunately, this well executed system of types,
conversion, and casting can be harnessed to build error free applications.
### Resources
- [Casting and type conversions (C# programming guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions)