Converting Overview
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 is capable of having, 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. 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 two objects. In addition to supporting implicit conversion, the .NET Framework supports explicit conversion through the System.Convert class, which provides methods to convert between types.
Anteckning
Individual languages may also provide ways to perform explicit conversions. For example, C# uses casting operators; Visual Basic uses compiler-implemented conversion functions such as CType, CInt, and DirectCast.
Widening conversion and narrowing conversion are both supported by the common language runtime. For example, the value that is represented as a 32-bit signed integer can be converted into a 64-bit signed integer. This is an example of a widening conversion. The opposite conversion (from 64-bit to 32-bit) is an example of a narrowing conversion. Information is never lost as the result of a widening conversion (although precision may be); however, information can be lost during a narrowing conversion. For a list of widening conversions, see the Type Conversion Tables.
The following example shows a widening conversion, where the Int32 value MyInt is converted to an Int64 value. This conversion is accomplished implicitly, without the use of the Convert class or any other conversion method or operator.
Dim MyInt As Integer = 1234567891
Dim MyBigInt As Long = MyInt
Console.WriteLine(MyBigInt) ' Displays 1234567891
int MyInt = 1234567891;
long MyBigInt = MyInt;
Console.WriteLine(MyBigInt); // Displays 1234567891
The following example shows a narrowing conversion, where the Int64 value MyBigInt is converted to a Int32 value. Such a narrowing conversion must always be performed explicitly in C#, and it must be performed explicitly in Visual Basic if Option Strict is set on. In this example, the ToInt32 method is called to perform the conversion.
Dim MyBigInt As Long = 1234567891
' exception handler: narrowing conversions can overflow
Try
Dim MyInt As Integer = Convert.ToInt32(MyBigInt)
Console.WriteLine(MyInt) ' Displays 1234567891
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to an integer.", _
MyBigInt)
End Try
long MyBigInt = 1234567891;
// exception handler: narrowing conversions can overflow
try
{
int MyInt = Convert.ToInt32(MyBigInt);
Console.WriteLine(MyBigInt); // Displays 1234567891
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to an integer.",
MyBigInt);
}