Behind the Scenes Look at C#: Type Conversions - Implicit Type Conversions (Built-In Value-Types)
(Page 4 of 6 )
Implicit conversion on types are those conversion operations that the C# compiler performs without warning us. Actually the C# compiler doesn't warn you about implicit conversions because there's no loss of data with those operations and they are save operations. The implicit type operation performs conversion from a small type to a larger one; that's why we don't lose our data. For example, you can assign a variable of type short (which contains the maximum value of this type) to a variable of type int; you will not lose any data because int is bigger than short, and the bits will be copied into the int variable exactly.
But why do we need implicit conversions? It's a matter of memory management. We have different types to hold different ranges of numbers. We use the small types when our scenario requires small values, and we use a larger types when the stored values are large, to save memory. If we had only one type to represent numbers, we wouldn't need to convert between types. In fact, we have many types that hold different ranges to save memory, and we can use type conversion to convert between types. Take a look at the following example:
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
short x = 9;
int y = 8;
int result = x + y; // Implicit conversion occurs here
Console.WriteLine("the value of the result variable = " + result);
Console.WriteLine("calling the GetLong method and passing result");
long i = GetLong(result); // implicit conversion occurs here again
Console.WriteLine("i = {0}", i);
Console.ReadLine();
}
static long GetLong(long temp)
{
return 10 * temp;
}
}
}
The result is:

In this simple example the compiler performed implicit conversion operations between types. In the first operation, when we add x to y, the addition operator (+) doesn't work with the short data type, so it converts the short variable to an int data type implicitly. The second conversion operation happens when we pass the result variable to the method GetLong, that accepts a parameter of type long; the Compiler converts the argument result from an int data type to long data type, then passes it to the method implicitly.
The compiler does this all the time; you don't have to remember that because there's no loss of data. This conversion operation is called asymmetrical operation. This means that you can do this type of conversion, but you can't do the reverse operation implicitly. In other words, you can't assign a value of a large type to a small one implicitly, because you may lose data. You need explicit conversion in order to do this operation.
Next: Explicit Type Conversions (Built-In Value-Types) >>
More C# Articles
More By Michael Youssef