0% found this document useful (0 votes)
11 views5 pages

TypeCastin PG

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

TypeCastin PG

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Type Casting or Type Conversion

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.

In this module, we'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.

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.

To perform data conversion, you can use one of several techniques:

 Use a helper method on the data type


 Use a helper method on the variable
 Use the Convert class' methods

Is it possible that attempting to change the value's data type would result in a
loss of information?

Lets understand this by adding some lines here

int myInt = 3;
Console.WriteLine($"int: {myInt}");

decimal myDecimal = myInt;


Console.WriteLine($"decimal: {myDecimal}");

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

decimal myDecimal = 3.14m;


Console.WriteLine($"decimal: {myDecimal}");

int myInt = (int)myDecimal;


Console.WriteLine($"int: {myInt}");

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.

We will write small tests to better understand the behaviors by an example.

decimal myDecimal = 1.23456789m;


float myFloat = (float)myDecimal;

Console.WriteLine($"Decimal: {myDecimal}");
Console.WriteLine($"Float : {myFloat}");
O/P:
Decimal: 1.23456789
Float : 1.2345679

Performing Data Conversions

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:

 Use a helper method on the variable


 Use a helper method on the data type
 Use the Convert class' methods

Use ToString() to convert a number to a string

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.

string first = "5";


string second = "7";
int sum = int.Parse(first) + int.Parse(second);
Console.WriteLine(sum);

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 C# compiler and runtime expects us to prevent "illegal" conversions.

We can mitigate the runtime exception in several ways.

The easiest way to mitigate this situation is by using TryParse(), which is a better version of
the Parse() method.

string first = "5";


string second = "7";
int sum = int.Parse(first) + int.Parse(second);
Console.WriteLine(sum);

Converting a string representation of number to an integer, using


the int.TryParse() method in C#. If the string cannot be converted, then
the int.TryParse() method returns false i.e. a Boolean value.

string first = "5";


string second = "7";
int sum;
sum = int.Parse(first) + int.Parse(second);
bool result = int.TryParse(first+second, out sum);
Console.Write(sum + " " + result);

Convert a string to a int using the Convert class


The Convert class has many helper methods to convert a value from one type into
another.

string value1 = "5";


string value2 = "7";
int result = Convert.ToInt32(value1) * Convert.ToInt32(value2);
Console.WriteLine(result);

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.

Compare casting and converting a decimal into an int


what happens when you attempt to cast a decimal into an int (a narrowing conversion)
versus
using the Convert.ToInt32() method to convert the same decimal into an int.

4
int value = (int)1.5m; // casting truncates
Console.WriteLine(value);

int value2 = Convert.ToInt32(1.5m); // converting rounds up


Console.WriteLine(value2);

Output:
1
2

Casting truncates and converting rounds

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.

several important concepts of data conversion and casting:

 Prevent a runtime error while performing a data conversion


 Perform an explicit cast to tell the compiler you understand the risk of losing data
 Rely on the compiler to perform an implicit cast when performing an expanding
conversion
 Use the () cast operator and the data type to perform a cast (for
example, (int)myDecimal)
 Use the Convert class when you want to perform a narrowing conversion, but want
to perform rounding, not a truncation of information

You might also like