Implicit Conversions

Implicit conversion requires no work on your part and no additional code. Consider the code shown here:

var1 = var2;

This assignment may involve an implicit conversion if the type of var2 can be implicitly converted into the type of var1 , but it could just as easily involve two variables with the same type, and no implicit conversion is necessary. For example, the values of ushort and char are effectively interchangeable, because both store a number between 0 and 65535. You can convert values between these types implicitly, as illustrated by the following code:

ushort destinationVar;
char sourceVar = ‘a’;
destinationVar = sourceVar;
Console.WriteLine(“sourceVar val: {0}”, sourceVar);
Console.WriteLine(“destinationVar val: {0}”, destinationVar);

Here, the value stored in sourceVar is placed in destinationVar . When you output the variables with the two Console.WriteLine() commands, you get the following output:

sourceVar val: a
destinationVar val: 97

Even though the two variables store the same information, they are interpreted in different ways using their type. There are many implicit conversions of simple types; bool and string have no implicit conversions, but the numeric types have a few. For reference, the following table shows the numeric conversions that the compiler can perform implicitly (remember that char s are stored as numbers, so char counts as a numeric type):

Type Can Safely Be Converted To
Byte short, ushort, int, uint, long, ulong, float, double, decimal
Sbyte short, int, long, float, double, decimal
Short int, long, float, double, decimal
Ushort int, uint, long, ulong, float, double, decimal
Int long, float, double, decimal
Uint long, ulong, float, double, decimal
Long float, double, decimal
Ulong float, double, decimal
Float double
Char ushort, int, uint, long, ulong, float, double, decimal

You may also like...