Pages

Wednesday, 22 July 2015

Types of Conversions

Types of Conversions

There are a number of standard, predefined conversions for the numeric and reference types, as following figure:

Numeric Conversions

Any numeric type can be converted into any other numeric type, as illustrated in following figure. Some of the conversions are implicit conversions, and others must be explicit.

Implicit Numeric Conversions

The figure demonstrates that, as you would expect, there is an implicit conversion between numeric types that occupy fewer bits to those that occupy more bits.
  • There is an implicit conversion from the source type to the target type if there is a path, following the arrows, from the source type to the target type.
  • Any numeric conversion for which there is not a path following the arrows from the source type to the target type must be an explicit conversion.

Explicit Numeric Conversions

With the explicit conversions, however, there is the possibility of losing data—so it’s important for you as the programmer to know how a conversion will handle that loss if it occurs.

Integer Type to Integer Type

Following figure shows the behavior of the integer-to-integer explicit conversions. In the checked case, if the conversion loses data, the operation raises an OverflowException exception. In the unchecked case, any lost bits go unreported.

float or double to Integer Type

When converting a floating-point type to an integer type, the value is rounded toward 0 to the nearest integer. Following figure illustrates the conversion conditions. If the rounded value is not within the range of the target type, then
  • The CLR raises an OverflowException exception if the overflow checking context is checked.
  • C# does not define what its value should be if the context is unchecked.

decimal to Integer Type

When converting from decimal to the integer types, the CLR raises an OverflowException exception if the resulting value is not within the target type’s range.

double to float

Values of type float occupy 32 bits, and values of type double occupy 64 bits. When a double is rounded to a float, the double type value is rounded to the nearest float type value.
  • If the value is too small to be represented by a float, the value is set to either positive or negative 0.
  • If the value is too large to be represented by a float, the value is set to either positive or negative infinity.

float or double to decimal

Following action will occur when converting float or double to decimal:
  • If the value is too small to be represented by the decimal type, the result is set to 0.
  • If the value is too large, the CLR raises an OverflowException exception.

decimal to float or double

Conversions from decimal to the floating-point types always succeed. There might, however, be a loss of precision.

0 comments:

Post a Comment