C# - Implicit and Explicit Type Conversion

Implicit Conversions

Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

When one type of data is assigned to another type of variable, an implicit type conversion will take place automatically if

  • The two types are compatible.
  • The destination type has a range that is greater than the source type.

When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, and both int and byte are compatible integer types, so an implicit conversion can be applied.

 // Implicit conversion. num long can
 // hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;

Explicit Conversions

Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted. The following program casts a double to an int. The program will not compile without the cast.

class Test
    static void Main()
        double x = 1234.7;
        int a;
        // Cast double to int.
        a = (int)x;

When a cast involves a narrowing conversion, information might be lost. For example, when casting a long into an int, information will be lost if the long’s value is greater than the range of an int because its high-order bits are removed. When a floating-point value is cast to an integer type, the fractional component will also be lost due to truncation.

KeenTPoint Video Tutorial - C# Type Conversion