TypeCastin PG
TypeCastin PG
Here in .Net application,We work on many data that is in a mix of data types. we'll build a
console application and collect all of the input as strings.
Because the input is initially input as a string, we need to occasionally change values from
one data type into another in the code.
A simple example is any mathematical operation we want to perform with string data.
we would first need to change the value into a numeric data type, like int, and then we
could manipulate the operation.
Alternatively, we may want to format and output a numeric value for a summary
report using string interpolation.
We use different techniques to change a data type when necessary. we 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, we're able to take control of the data in our applications,
knowing when to apply the correct technique to change data types as needed.
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.
There are multiple techniques to perform a data type conversion. The technique we choose
depends on our answer to two important questions:
Is it possible that attempting to change the value's data type would throw
an exception at run time?
Is it possible that attempting to change the value's data type would result in
a loss of information?
The C# compiler attempts to accommodate wer code, but doesn't compile operations that
could result in an exception.
int first = 2;
string second = "4";
int result = first + second;
Console.WriteLine(result);
Here, we're attempting to add the values 2 and 4. The value 4 is of type string. Will this
work?
But why can't the C# Compiler just handle the error? After all, we can do the opposite to
concatenate a number to a string and save it in a string variable. Here, we change the data
type of the result variable from int to string.
int first = 2;
string second = "4";
string result = first + second;
Console.WriteLine(result);
The output is mathematically incorrect but completes by combining the values as the
characters "2" and "4".
the first code example where the result variable is of type int. The code with the error
message.
Why can't the C# compiler figure out that you want to treat the
variable second containing 4 as a number, not a string?
1
The C# compiler sees a potential problem in the making.
The variable second is of type string, so it might be set to a different value like "hello".
If the C# compiler attempted to convert "hello" to a number that would cause an exception
at runtime.
To avoid this possibility, the C# compiler doesn't implicitly perform the conversion
from string to int for you.
From the C# compiler's perspective, the safer operation would be to convert int into
a string and perform concatenation instead.
If you intend to perform addition using a string, the C# compiler requires you to take more
explicit control of the process of data conversion. In other words, it forces you to be more
involved so that you can put the proper precautions in place to handle the possibility that
the conversion could throw an exception.
If you need to change a value from the original data type to a new data type and the
change could produce an exception at run time, you must perform a data conversion.
Is it possible that attempting to change the value's data type would result in a
loss of information?
int myInt = 3;
Console.WriteLine($"int: {myInt}");
O/P:
int: 3
decimal: 3
The key to this example is this line of code: decimal myDecimal = myInt;
Since any int value can easily fit inside of a decimal, the compiler performs the conversion.
The term widening conversion means that you're attempting to convert a value from a
data type that could hold less information to a data type that can hold more information.
Here a value stored in a variable of type int converted to a variable of type decimal,
doesn't lose information.
When you know you're performing a widening conversion, you can rely on implicit
conversion. The compiler handles implicit conversions.
Perform a cast
2
To perform a cast, you use the casting operator () to surround a data type, then place it
next to the variable you want to convert (example: (int)myDecimal).
You perform an explicit conversion to the defined cast data type (int).
O/P:
decimal: 3.14
int: 3
The variable myDecimal holds a value that has precision after the decimal point. By adding
the casting instruction (int), you're telling the C# compiler that you understand it's possible
you'll lose that precision, and in this situation, it's fine. You're telling the compiler that
you're performing an intentional conversion, an explicit conversion.
The term narrowing conversion means that you're attempting to convert a value from a
data type that can hold more information to a data type that can hold less information.
In this case, you may lose information such as precision (that is, the number of values after
the decimal point).
An example is converting value stored in a variable of type decimal into a variable of
type int. If you print the two values, you would possibly notice the loss of information.
When you know you're performing a narrowing conversion, you need to perform a cast.
Casting is an instruction to the C# compiler that you know precision may be lost, but
you're willing to accept it.
If you're unsure whether you lose data in the conversion, write code to perform a
conversion in two different ways and observe the changes.
Console.WriteLine($"Decimal: {myDecimal}");
Console.WriteLine($"Float : {myFloat}");
O/P:
Decimal: 1.23456789
Float : 1.2345679
When a value change from one data type into another could cause a runtime exception,
and you should perform data conversion. For data conversions, there are three techniques
you can use:
We are using the ToString() method to explicitly convert int values into strings.
int first = 5;
int second = 7;
string message = first.ToString() + second.ToString();
Console.WriteLine(message);
O/P:
57
3
Convert a string to an int using the Parse() helper method
The numeric data types have a Parse() method, which converts a string into the given
data type. In this case, we use the Parse() method to convert two strings into int values,
then add them together.
O/P:
12
The potential problem with the previous code example? What if either of the
variables first or second are set to values that can't be converted to an int? An exception is
thrown at runtime.
The easiest way to mitigate this situation is by using TryParse(), which is a better version of
the Parse() method.
O/P :
35
The Convert class is best for converting fractional numbers into whole numbers (int)
because it rounds up the way we would expect.
4
int value = (int)1.5m; // casting truncates
Console.WriteLine(value);
Output:
1
2
When you're casting int value = (int)1.5m;, the value of the float is truncated so the
result is 1, meaning the value after the decimal is ignored completely. You could change
the literal float to 1.999m and the result of casting would be the same.
When you're converting using Convert.ToInt32(), the literal float value is properly
rounded up to 2. If you changed the literal value to 1.499m, it would be rounded down to 1.