This documentation is archived and is not being maintained.

Type Conversion in the .NET Framework

Every value has an associated type, which defines attributes such as the amount of space allocated to the value, the range of possible values it can have, and the members that it makes available. Many values can be expressed as more than one type. For example, the value 4 can be expressed as an integer or a floating-point value. Type conversion creates a value in a new type that is equivalent to the value of an old type, but does not necessarily preserve the identity (or exact value) of the original object.

The .NET Framework provides several features that support type conversion. These include the following: 

Widening conversions involve the creation of a new value from the value of an existing type that has either a more restrictive range or a more restricted member list than the target type. Widening conversions cannot result in data loss (although they may result in a loss of precision). Because data cannot be lost, compilers can handle the conversion implicitly or transparently, without requiring the use of an explicit conversion method or a casting operator.

NoteNote

Although code that performs an implicit conversion can call a conversion method or use a casting operator, their use is not required by compilers that support implicit conversions.

For example, the Decimal type supports implicit conversions from Byte, Char, Int16, Int32, Int64, SByte, UInt16, UInt32, and UInt64 values. The following example illustrates some of these implicit conversions in assigning values to a Decimal variable.

No code example is currently available or this language may not be supported.

If a particular language compiler supports custom operators, you can also define implicit conversions in your own custom types. The following example provides a partial implementation of a signed byte data type named ByteWithSign that uses sign-and-magnitude representation. It supports implicit conversion of Byte and SByte values to ByteWithSign values.

No code example is currently available or this language may not be supported.

Client code can then declare a ByteWithSign variable and assign it Byte and SByte values without performing any explicit conversions or using any casting operators, as the following example shows.

No code example is currently available or this language may not be supported.

Back to top

Narrowing conversions involve the creation of a new value from the value of an existing type that has either a greater range or a larger member list than the target type. Because a narrowing conversion can result in a loss of data, compilers often require that the conversion be made explicit through a call to a conversion method or a casting operator. That is, the conversion must be handled explicitly in developer code.

NoteNote

The major purpose of requiring a conversion method or casting operator for narrowing conversions is to make the developer aware of the possibility of data loss or an OverflowException so that it can be handled in code. However, some compilers can relax this requirement. For example, in Visual Basic, if Option Strict is off (its default setting), the Visual Basic compiler tries to perform narrowing conversions implicitly.

For example, the UInt32, Int64, and UInt64 data types have ranges that exceed that the Int32 data type, as the following table shows.

Type

Comparison with range of Int32

Int64

Int64::MaxValue is greater than Int32::MaxValue, and Int64::MinValue is less than (has a greater negative range than) Int32::MinValue.

UInt32

UInt32::MaxValue is greater than Int32::MaxValue.

UInt64

UInt64::MaxValue is greater than Int32::MaxValue.

To handle such narrowing conversions, the .NET Framework allows types to define an Explicit operator. Individual language compilers can then implement this operator using their own syntax, or a member of the Convert class can be called to perform the conversion. (For more information about the Convert class, see The Convert Class later in this topic.) The following example illustrates the use of language features to handle the explicit conversion of these potentially out-of-range integer values to Int32 values.

No code example is currently available or this language may not be supported.

Explicit conversions can produce different results in different languages, and these results can differ from the value returned by the corresponding Convert method. For example, if the Double value 12.63251 is converted to an Int32, both the Visual Basic CInt method and the .NET Framework Convert::ToInt32(Double) method round the Double to return a value of 13, but the C# (int) operator truncates the Double to return a value of 12. Similarly, the C# (int) operator does not support Boolean-to-integer conversion, but the Visual Basic CInt method converts a value of true to -1. On the other hand, the Convert::ToInt32(Boolean) method converts a value of true to 1.

Most compilers allow explicit conversions to be performed in a checked or unchecked manner. When a checked conversion is performed, an OverflowException is thrown when the value of the type to be converted is outside the range of the target type. When an unchecked conversion is performed under the same conditions, the conversion might not throw an exception, but the exact behavior becomes undefined and an incorrect value might result.

NoteNote

In C#, checked conversions can be performed by using the checked keyword together with a casting operator, or by specifying the /checked+ compiler option. Conversely, unchecked conversions can be performed by using the unchecked keyword together with the casting operator, or by specifying the /checked- compiler option. By default, explicit conversions are unchecked. In Visual Basic, checked conversions can be performed by clearing the Remove integer overflow checks check box in the project's Advanced Compiler Settings dialog box, or by specifying the /removeintchecks- compiler option. Conversely, unchecked conversions can be performed by selecting the Remove integer overflow checks check box in the project's Advanced Compiler Settings dialog box or by specifying the /removeintchecks+ compiler option. By default, explicit conversions are checked.

The following C# example uses the checked and unchecked keywords to illustrate the difference in behavior when a value outside the range of a Byte is converted to a Byte. The checked conversion throws an exception, but the unchecked conversion assigns Byte::MaxValue to the Byte variable.


int largeValue = Int32.MaxValue;
byte newValue;

try {
   newValue = unchecked((byte) largeValue);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", 
                     largeValue.GetType().Name, largeValue,
                     newValue.GetType().Name, newValue);
}
catch (OverflowException) {
   Console.WriteLine("{0} is outside the range of the Byte data type.", 
                     largeValue);
}

try {
   newValue = checked((byte) largeValue);
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", 
                     largeValue.GetType().Name, largeValue,
                     newValue.GetType().Name, newValue);
}
catch (OverflowException) {
   Console.WriteLine("{0} is outside the range of the Byte data type.", 
                     largeValue);
}
// The example displays the following output:
//    Converted the Int32 value 2147483647 to the Byte value 255.
//    2147483647 is outside the range of the Byte data type.


If a particular language compiler supports custom overloaded operators, you can also define explicit conversions in your own custom types. The following example provides a partial implementation of a signed byte data type named ByteWithSign that uses sign-and-magnitude representation. It supports explicit conversion of Int32 and UInt32 values to ByteWithSign values.

No code example is currently available or this language may not be supported.

Client code can then declare a ByteWithSign variable and assign it Int32 and UInt32 values if the assignments include a casting operator or a conversion method, as the following example shows.

No code example is currently available or this language may not be supported.

Back to top

To support the conversion of any type to a common language runtime base type, the .NET Framework provides the IConvertible interface. The implementing type is required to provide the following:

  • A method that returns the TypeCode of the implementing type.

  • Methods to convert the implementing type to each common language runtime base type (Boolean, Byte, DateTime, Decimal, Double, and so on).

  • A generalized conversion method to convert an instance of the implementing type to another specified type. Conversions that are not supported should throw an InvalidCastException.

Each common language runtime base type (that is, the Boolean, Byte, Char, DateTime, Decimal, Double, Int16, Int32, Int64, SByte, Single, String, UInt16, UInt32, and UInt64), as well as the DBNull and Enum types, implement the IConvertible interface. However, these are explicit interface implementations; the conversion method can be called only through an IConvertible interface variable, as the following example shows. This example converts an Int32 value to its equivalent Char value.

No code example is currently available or this language may not be supported.

The requirement to call the conversion method on its interface rather than on the implementing type makes explicit interface implementations relatively expensive. Instead, we recommend that you call the appropriate member of the Convert class to convert between common language runtime base types. For more information, see the next section, The Convert Class.

NoteNote

In addition to the IConvertible interface and the Convert class provided by the .NET Framework, individual languages may also provide ways to perform conversions. For example, C# uses casting operators; Visual Basic uses compiler-implemented conversion functions such as CType, CInt, and DirectCast.

For the most part, the IConvertible interface is designed to support conversion between the base types in the .NET Framework. However, the interface can also be implemented by a custom type to support conversion of that type to other custom types. For more information, see the section Custom Conversions with the ChangeType Method later in this topic.

Back to top

Although each base type's IConvertible interface implementation can be called to perform a type conversion, calling the methods of the System::Convert class is the recommended language-neutral way to convert from one base type to another. In addition, the Convert::ChangeType(Object, Type, IFormatProvider) method can be used to convert from a specified custom type to another type.

Conversions Between Base Types

The Convert class provides a language-neutral way to perform conversions between base types and is available to all languages that target the common language runtime. It provides a complete set of methods for both widening and narrowing conversions, and throws an InvalidCastException for conversions that are not supported (such as the conversion of a DateTime value to an integer value). Narrowing conversions are performed in a checked context, and an OverflowException is thrown if the conversion fails.

Important noteImportant

Because the Convert class includes methods to convert to and from each base type, it eliminates the need to call each base type's IConvertible explicit interface implementation.

The following example illustrates the use of the System::Convert class to perform several widening and narrowing conversions between .NET Framework base types.

No code example is currently available or this language may not be supported.

In some cases, particularly when converting to and from floating-point values, a conversion may involve a loss of precision, even though it does not throw an OverflowException. The following example illustrates this loss of precision. In the first case, a Decimal value has less precision (fewer significant digits) when it is converted to a Double. In the second case, a Double value is rounded from 42.72 to 43 in order to complete the conversion.

No code example is currently available or this language may not be supported.

For a table that lists both the widening and narrowing conversions supported by the Convert class, see Type Conversion Tables.

Custom Conversions with the ChangeType Method

In addition to supporting conversions to each of the base types, the Convert class can be used to convert a custom type to one or more predefined types. This conversion is performed by the Convert::ChangeType(Object, Type, IFormatProvider) method, which in turn wraps a call to the IConvertible::ToType method of the value parameter. This means that the object represented by the value parameter must provide an implementation of the IConvertible interface.

The following example illustrates a possible implementation of the IConvertible interface that allows a TemperatureCelsius object to be converted to a TemperatureFahrenheit object and vice versa. The example defines a base class, Temperature, that implements the IConvertible interface and overrides the Object::ToString method. The derived TemperatureCelsius and TemperatureFahrenheit classes each override the ToType and the ToString methods of the base class.

No code example is currently available or this language may not be supported.

The following example illustrates several calls to these IConvertible implementations to convert TemperatureCelsius objects to TemperatureFahrenheit objects and vice versa.

No code example is currently available or this language may not be supported.

Back to top

The .NET Framework also allows you to define a type converter for a custom type by extending the System.ComponentModel::TypeConverter class and associating the type converter with the type through a System.ComponentModel::TypeConverterAttribute attribute. The following table highlights the differences between this approach and implementing the IConvertible interface for a custom type.

NoteNote

Design-time support can be provided for a custom type only if it has a type converter defined for it.

Conversion using TypeConverter

Conversion using IConvertible

Is implemented for a custom type by deriving a separate class from TypeConverter. This derived class is associated with the custom type by applying a TypeConverterAttribute attribute.

Is implemented by a custom type to perform conversion. A user of the type invokes an IConvertible conversion method on the type.

Can be used both at design time and at run time.

Can be used only at run time.

Uses reflection; therefore, is slower than conversion enabled by IConvertible.

Does not use reflection.

Allows two-way type conversions from the custom type to other data types, and from other data types to the custom type. For example, a TypeConverter defined for MyType allows conversions from MyType to String, and from String to MyType.

Allows conversion from a custom type to other data types, but not from other data types to the custom type.

For more information about using type converters to perform conversions, see System.ComponentModel::TypeConverter.

Back to top

Show: