Behind the Scenes Look at C#: Type Conversions - The Value-Type Example
(Page 2 of 6 )
Take a look at this example:
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
uint x = 65540; // the max value of uint16 + 5
ushort y = (ushort)x;
Console.WriteLine("The value of y after the casting = {0}",y);
Console.ReadLine();
}
}
}
Run the example:

The value of y = 4 after the casting? Yes, we have lost our data and we received another value. If you understand the fundamental concepts of type conversion, you will know that this is exactly the expected behavior. Think about it, the maximum value of UInt16 is 65535, which equals 1111111111111111 (16 bits). When we added 5 to the maximum value and assigned it to a variable of type UInt32 we received the value 4 because the bits have been shifted. The value 65540 with the UInt32 structure represented in bits as:
00000000 00000001 00000000 00000100
and when we used the cast operator to FORM THIS VALUE INTO ANOTHER TYPE the bits were truncated to fit in the UInt16 structure (represented in C# using the keyword short). This is because this type can be represented as 16 bits only, while the UInt32 structure can be represented 32 bits. So the following bits have been copied to the y variable as a result from the casting operation.
00000000 00000100
That's why we receive the value 4 out of this code. As you can see, the cast is just a way to tell that you need to do some operations, and you know the side effect of the type conversion. Let's address this example with reference types.
Next: The Reference-Type Example >>
More C# Articles
More By Michael Youssef