Behind the Scenes Look at C#: Type Conversions - Explicit Type Conversions (Built-In Value-Types)
(Page 5 of 6 )
Let's try to run the following code in VS.NET and see what will happen.
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
long x = 100;
int y = x; // can I write such code?
decimal i = 3.45m;
float o = i; // can I write such code?
}
}
}
This code can't be compiled. It generates the following errors in the TasList window:

The compiler can't perform an implicit type conversion operation from a larger type to a smaller one because it might lose data. Although in our example the value 100 is in the valid range of both the long and the int data type (and the same with the decimal and float data types), the compiler can't implicitly convert from type long to type int. You need to explicitly use the cast operation to do this operation.
So conversions from one type to another smaller type (that contains fewer bits) need an explicit conversion operation because it might lose some data if the value of the type is larger than the maximum value range of the type that we convert to. You must use the cast operation to perform the explicit conversion operation. You use the case operator in the same way as in C; you use parentheses and the type that you want to convert to enclosed in the parentheses, then you put them on the left of the variable or the value that you want to convert. Let's modify the above example to use the cast operator.
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
long x = 100;
int y = (int)x; // this will work
Console.WriteLine(y);
decimal i = 3.45m;
float o = (float)i; // this will work
Console.WriteLine(o);
Console.ReadLine();
}
}
}
Compile and run the example to get the following result, as we expect:

We have looked at the bits problem in the value-type example and what would happen when you cast a value that exceeds the maximum value of the type we cast to. So I will not discuss it here again. Just be careful when using explicit casting operations, because you might get an unexpected value. If you get a value like this, try to think about the bits and read the value-type example section again. There are two keywords that can be very useful at this point, the checked and unchecked keywords. Let's take a look.
Next: The Checked and Unchecked Keywords >>
More C# Articles
More By Michael Youssef