Type Conversion in C#

Type Conversion



C# is a strongly typed language, so when you are assigning values of variables from one type to another,
you must take extra care to ensure that the assignment is compatible. Consider the following statements
where you have two variables — one of type int and another of type short :
int num;
short sNum = 20;
The following statement assigns the value of sNum to num :
num = sNum; //---OK---
This statement works because you ' re are assigning the value of a type ( short ) whose range is smaller
than that of the target type ( int ). In such instances, C# allows the assignment to occur, and that ' s known
as implicit conversion .
Converting a value from a smaller range to a bigger range is known as widening .
The following table shows the implicit conversion between the different built - in types supported by C#.

Convert from (type) To (type)
sbyte short, int, long, float, double, or decimal
byte short, ushort, int, uint, long, ulong, float, double, or decimal
short int, long, float, double, or decimal
ushort int, uint, long, ulong, float, double, or decimal
int long, float, double, or decimal
uint long, ulong, float, double, or decimal
long float, double, or decimal
char ushort, int, uint, long,ulong,float, double,or decimal
float double
ulong float, double, or decimal

If you try to assign the value of a type whose range is bigger than the target type, C# will raise an error.
Consider the following example:

num = 5;
sNum = num; //---not allowed---

In this case, num is of type int and it may contain a big number (such as 40,000). When assigning it to
a variable of type short , that could cause a loss of data. To allow the assignment to proceed, C# requires
you to explicitly type - cast (convert) the value to the target type. This process is known as explicit
conversion .
Converting a value from a bigger range to a smaller range is known as narrowing.
Narrowing can result in a loss of data, so be careful when performing
a narrowing operation.
The preceding statement could be made valid when you perform a type casting operation by
prefixing the variable that you want to assign with the target type in parentheses:

num = 5;
sNum = (short) num; //---sNum is now 5---

When performing type casting, you are solely responsible for ensuring that the target variable can
contain the value assigned and that no loss of data will happen. In the following example, the assignment
will cause an overflow, changing the value of num to  25536, which is not the expected value:
By default, Visual Studio 2008 checks statements involving constant assignments for
overflow during compile time. However, this checking is not enforced for statements
whose values cannot be determined at runtime.

int num = 40000;
short sNum;
sNum =(short) num; //--- -25536; no exception is raised ---

To ensure that an exception is thrown during runtime when an overflow occurs, you can use the
checked keyword, which is used to explicitly enable overflow - checking for integral - type arithmetic

//operations and conversions:
try
{
sNum = checked((short)num); //---overflow exception---
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}

If you try to initialize a variable with a value exceeding its range, Visual Studio 2008 raises an error at
compile time, as the following shows:

int num = 400000 * 400000;
//---overflows at compile time in checked mode
To turn off the automatic check mode, use the unchecked keyword, like this:
unchecked
{
int num = 400000 * 400000;
}

The compiler will now ignore the error and proceed with the compilation.
Another way to perform conversion is to use the System.Convert class to perform the conversion for
you. The System.Convert class converts the value of a variable from one type into another type. It can
convert a value to one of the following types:

Boolean Int16 UInt32 Decimal
Char Int32 UInt64 DateTime
SByte Int64 Single String
Byte UInt16 Double
//Using an earlier example, you can convert a value to Int16 using the following statement:
sNum = Convert.ToInt16(num);
//If a number is too big (or too small) to be converted to a particular type, an overflow exception is thrown,
//and you need to catch the exception:
int num = 40000;
short sNum;
try
{
sNum = Convert.ToInt16(num); //---overflow exception---
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}

When converting floating point numbers to integer values, you need to be aware of one subtle difference
between type casting and using the Convert class. When you perform a type casting on a floating point
number, it truncates the fractional part, but the Convert class performs numerical rounding for you,
as the following example shows:

int num;
float price = 5.99F;
num = (int)price; //---num is 5---
num = Convert.ToInt16(price); //---num is 6---

When converting a string value type to a numerical type, you can use the Parse() method that is
available to all built in numeric types (such as int , float , double , and so on). Here ' s how you can
convert the value stored in the str variable into an integer:

string str = “5";
int num = int.Parse(str);
Beware that using the Parse() method may trigger an exception, as demonstrated here:
string str = “5a";
int num = int.Parse(str); //---format exception---

This statement causes a format exception to be raised during runtime because the Parse() method
cannot perform the conversion. A safer way would be to use the TryParse() method, which will try to
perform the conversion. It returns a false if the conversion fails, or else it returns the converted value in
the out parameter:

int num;
string str = “5a";
if (int.TryParse(str, out num))
Console.WriteLine(num);
else
Console.WriteLine(“Cannot convert");


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: