Implicit Type Conversion

Implicit Type Conversion in c#

Implicit (hidden) type conversion is possible only when there is no risk of data loss during the conversion, i.e. when converting from a lower range type to a larger range (e.g. from int to long). To make an implicit conversion it is not necessary to use any operator and therefore such transformation is called implicit. The implicit conversion is done automatically by the compiler when you assign a value with lower range to a variable with larger range or if the expression has several types with different ranges. In such case the conversion is executed into the type with the highest range.

Implicit Type Conversion – Examples


Here is an example of implicit type conversion:

http://www.csharp2018.tk/2018/06/implicit-type-conversion.html
http://www.csharp2018.tk/2018/06/implicit-type-conversion.html


In the example we create a variable myInt of type int and assign it the value 5. After that we create a variable myLong of type long and assign it the value contained in myInt. The value stored in myLong is automatically converted from type int to type long. Finally, we output the result from adding the two variables. Because the variables are from different types they are automatically converted to the type with the greater range, i.e. to type long and the result that is printed on the console is long again. Indeed, the given parameter to the method Console.WriteLine() is of type long, but inside the method it will be converted again, this time to type string, so it can be printed on the console. This transformation is performed by the method Long.ToString().

Possible Implicit Conversions

Here are some possible implicit conversions of primitive data types in C#:
- sbyte → short, int, long, float, double, decimal;
- byte → short, ushort, int, uint, long, ulong, float, double, decimal;
- short → int, long, float, double, decimal;
- ushort → int, uint, long, ulong, float, double, decimal;
- char → ushort, int, uint, long, ulong, float, double, decimal (although char is a character type in some cases it may be regarded as a number and have a numeric type of behavior, it can even participate in numeric expressions);
- uint → long, ulong, float, double, decimal;
- int → long, float, double, decimal;
- long → float, double, decimal;
- ulong → float, double, decimal;
- float → double.
There is no data loss when converting types of smaller range to types with a larger range. The numerical value remains the same after conversion. There are a few exceptions. When you convert type int to type float (32-bit values), the difference is that int uses all bits for a whole number, whereas float has a part of bits used for representation of a fractional part. Hence, loss of precision is possible because of rounding when conversion from int to float is made. The same applies for the conversion of 64-bit long to 64-bit double.

Post a Comment

0 Comments