Convert.ChangeType Method (Object, Type, IFormatProvider)
Returns an object of the specified type whose value is equivalent to the specified object. A parameter supplies culture-specific formatting information.
Assembly: mscorlib (in mscorlib.dll)
Public Shared Function ChangeType ( value As Object, conversionType As Type, provider As IFormatProvider ) As Object
Parameters
- value
-
Type:
System.Object
An object that implements the IConvertible interface.
- conversionType
-
Type:
System.Type
The type of object to return.
- provider
-
Type:
System.IFormatProvider
An object that supplies culture-specific formatting information.
Return Value
Type: System.ObjectAn object whose type is conversionType and whose value is equivalent to value.
-or-
value, if the Type of value and conversionType are equal.
-or-
A null reference (Nothing in Visual Basic), if value is null and conversionType is not a value type.
| Exception | Condition |
|---|---|
| InvalidCastException | This conversion is not supported. -or- value is null and conversionType is a value type. -or- value does not implement the IConvertible interface. |
| FormatException | value is not in a format for conversionType recognized by provider. |
| OverflowException | value represents a number that is out of the range of conversionType. |
| ArgumentNullException | conversionType is null. |
ChangeType is a general-purpose conversion method that converts the object specified by value to conversionType. The value parameter can be an object of any type, and conversionType can also be a Type object that represents any base or custom type. For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. The method requires that conversion of value to conversionType be supported.
The provider parameter is an IFormatProvider implementation that supplies formatting information for the conversion. Whether and how this parameter is used depends on the underlying IConvertible implementation. If value is a base data type, provider is used only for the following conversions:
Conversion from a number to a string, or from a string to a number. provider must be a CultureInfo object, a NumberFormatInfo object, or a custom IFormatProvider implementation that returns a NumberFormatInfo object. However, because the ChangeType(Object, TypeCode, IFormatProvider) method performs the conversion using the default "G" format specifier, the provider parameter has no effect if value or the target type is an unsigned integer. If provider is null, the CultureInfo object that represents the current thread culture is used.
Conversion from a DateTime value to a string, or from a string to a DateTime value. provider must be a CultureInfo or DateTimeFormatInfo object. If provider is null, the CultureInfo object that represents the current thread culture is used.
If value is an application-defined type, its IConvertible implementation may use the provider parameter.
Notes to Callers:
The ChangeType(Object, Type, IFormatProvider) method can convert an enumeration value to another type. However, it cannot convert another type to an enumeration value, even if the source type is the underlying type of the enumeration. To convert a type to an enumeration value, use a casting operator (in C#) or a conversion function (in Visual Basic). The following example illustrates the conversion to and from a Continent enumeration value.
Public Enum Continent As Integer Africa = 0 Antarctica = 1 Asia = 2 Australia = 3 Europe = 4 NorthAmerica = 5 SouthAmerica = 6 End Enum Module Example Public Sub Main() ' Convert a Continent to a Double. Dim cont As Continent = Continent.NorthAmerica Console.WriteLine("{0:N2}", Convert.ChangeType(cont, GetType(Double))) ' Convert a Double to a Continent. Dim number As Double = 6.0 Try Console.WriteLine("{0}", Convert.ChangeType(number, GetType(Continent))) Catch e As InvalidCastException Console.WriteLine("Cannot convert a Double to a Continent") End Try Console.WriteLine("{0}", CType(number, Continent)) End Sub End Module ' The example displays the following output: ' 5.00 ' Cannot convert a Double to a Continent ' SouthAmerica
The Convert.ChangeType(Object, Type, IFormatProvider) method can convert a nullable type to another type. However, it cannot convert another type to a value of a nullable type, even if conversionType is the underlying type of the Nullable(Of T). To perform the conversion, you can use a casting operator (in C#) or a conversion function (in Visual Basic). The following example illustrates the conversion to and from a nullable type.
Module Example Public Sub Main() Dim intValue1 As Integer? = 12893 Dim dValue1 As Double = CType(Convert.ChangeType(intValue1, GetType(Double), Nothing), Double) Console.WriteLine("{0} ({1})--> {2} ({3})", intValue1, intValue1.GetType().Name, dValue1, dValue1.GetType().Name) Dim fValue1 As Single = 16.3478 Dim intValue2 As Integer? = CType(fValue1, Integer) Console.WriteLine("{0} ({1})--> {2} ({3})", fValue1, fValue1.GetType().Name, intValue2, intValue2.GetType().Name) End Sub End Module ' The example displays the following output: ' 12893 (Int32)--> 12893 (Double) ' 16.3478 (Single)--> 16 (Int32)
The following example defines a Temperature class that implements the IConvertible interface.
Imports System.Globalization Public Class Temperature : Implements IConvertible Private m_Temp As Decimal Public Sub New(temperature As Decimal) Me.m_Temp = temperature End Sub Public ReadOnly Property Celsius() As Decimal Get Return Me.m_Temp End Get End Property Public ReadOnly Property Kelvin() As Decimal Get Return Me.m_Temp + 273.15d End Get End Property Public ReadOnly Property Fahrenheit() As Decimal Get Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2) End Get End Property Public Overrides Function ToString() As String Return m_Temp.ToString("N2") & "°C" End Function ' IConvertible implementations. Public Function GetTypeCode() As TypeCode _ Implements IConvertible.GetTypeCode Return TypeCode.Object End Function Public Function ToBoolean(provider As IFormatProvider) As Boolean _ Implements IConvertible.ToBoolean If m_Temp = 0 Then Return False Else Return True End If End Function Public Function ToByte(provider As IFormatProvider) As Byte _ Implements IConvertible.ToByte If m_Temp < Byte.MinValue Or m_Temp > Byte.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the Byte type.", _ Me.m_Temp)) Else Return Decimal.ToByte(Me.m_Temp) End If End Function Public Function ToChar(provider As IFormatProvider) As Char _ Implements IConvertible.ToChar Throw New InvalidCastException("Temperature to Char conversion is not supported.") End Function Public Function ToDateTime(provider As IFormatProvider) As Date _ Implements IConvertible.ToDateTime Throw New InvalidCastException("Temperature to DateTime conversion is not supported.") End Function Public Function ToDecimal(provider As IFormatProvider) As Decimal _ Implements IConvertible.ToDecimal Return Me.m_Temp End Function Public Function ToDouble(provider As IFormatProvider) As Double _ Implements IConvertible.ToDouble Return Decimal.ToDouble(Me.m_Temp) End Function Public Function ToInt16(provider As IFormatProvider) As Int16 _ Implements IConvertible.ToInt16 If Me.m_Temp < Int16.MinValue Or Me.m_Temp > Int16.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the Int16 type.", _ Me.m_Temp)) Else Return Decimal.ToInt16(Me.m_Temp) End If End Function Public Function ToInt32(provider As IFormatProvider) As Int32 _ Implements IConvertible.ToInt32 If Me.m_Temp < Int32.MinValue Or Me.m_Temp > Int32.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the Int32 type.", _ Me.m_Temp)) Else Return Decimal.ToInt32(Me.m_Temp) End If End Function Public Function ToInt64(provider As IFormatProvider) As Int64 _ Implements IConvertible.ToInt64 If Me.m_Temp < Int64.MinValue Or Me.m_Temp > Int64.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the Int64 type.", _ Me.m_Temp)) Else Return Decimal.ToInt64(Me.m_Temp) End If End Function Public Function ToSByte(provider As IFormatProvider) As SByte _ Implements IConvertible.ToSByte If Me.m_Temp < SByte.MinValue Or Me.m_Temp > SByte.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the SByte type.", _ Me.m_Temp)) Else Return Decimal.ToSByte(Me.m_Temp) End If End Function Public Function ToSingle(provider As IFormatProvider) As Single _ Implements IConvertible.ToSingle Return Decimal.ToSingle(Me.m_Temp) End Function Public Overloads Function ToString(provider As IFormatProvider) As String _ Implements IConvertible.ToString Return m_Temp.ToString("N2", provider) & "°C" End Function Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object _ Implements IConvertible.ToType Select Case Type.GetTypeCode(conversionType) Case TypeCode.Boolean Return Me.ToBoolean(Nothing) Case TypeCode.Byte Return Me.ToByte(Nothing) Case TypeCode.Char Return Me.ToChar(Nothing) Case TypeCode.DateTime Return Me.ToDateTime(Nothing) Case TypeCode.Decimal Return Me.ToDecimal(Nothing) Case TypeCode.Double Return Me.ToDouble(Nothing) Case TypeCode.Int16 Return Me.ToInt16(Nothing) Case TypeCode.Int32 Return Me.ToInt32(Nothing) Case TypeCode.Int64 Return Me.ToInt64(Nothing) Case TypeCode.Object If GetType(Temperature).Equals(conversionType) Then Return Me Else Throw New InvalidCastException(String.Format("Conversion to a {0} is not supported.", _ conversionType.Name)) End If Case TypeCode.SByte Return Me.ToSByte(Nothing) Case TypeCode.Single Return Me.ToSingle(Nothing) Case TypeCode.String Return Me.ToString(provider) Case TypeCode.UInt16 Return Me.ToUInt16(Nothing) Case TypeCode.UInt32 Return Me.ToUInt32(Nothing) Case TypeCode.UInt64 Return Me.ToUInt64(Nothing) Case Else Throw New InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name)) End Select End Function Public Function ToUInt16(provider As IFormatProvider) As UInt16 _ Implements IConvertible.ToUInt16 If Me.m_Temp < UInt16.MinValue Or Me.m_Temp > UInt16.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the UInt16 type.", _ Me.m_Temp)) Else Return Decimal.ToUInt16(Me.m_Temp) End If End Function Public Function ToUInt32(provider As IFormatProvider) As UInt32 _ Implements IConvertible.ToUInt32 If Me.m_Temp < UInt32.MinValue Or Me.m_Temp > UInt32.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the UInt32 type.", _ Me.m_Temp)) Else Return Decimal.ToUInt32(Me.m_Temp) End If End Function Public Function ToUInt64(provider As IFormatProvider) As UInt64 _ Implements IConvertible.ToUInt64 If Me.m_Temp < UInt64.MinValue Or Me.m_Temp > UInt64.MaxValue Then Throw New OverflowException(String.Format("{0} is out of range of the UInt64 type.", _ Me.m_Temp)) Else Return Decimal.ToUInt64(Me.m_temp) End If End Function End Class
The following example creates an instance of the Temperature class and calls the ChangeType(Object, Type, IFormatProvider) method to convert it to the basic numeric types supported by the .NET Framework and to a String. It illustrates that the ChangeType method wraps a call to the source type's IConvertible implementation.
Module Example Public Sub Main() Dim cool As New Temperature(5) Dim targetTypes() As Type = { GetType(SByte), GetType(Int16), GetType(Int32), _ GetType(Int64), GetType(Byte), GetType(UInt16), _ GetType(UInt32), GetType(UInt64), GetType(Decimal), _ GetType(Single), GetType(Double), GetType(String) } Dim provider As New CultureInfo("fr-FR") For Each targetType As Type In targetTypes Try Dim value As Object = Convert.ChangeType(cool, targetType, provider) Console.WriteLine("Converted {0} {1} to {2} {3}.", _ cool.GetType().Name, cool.ToString(), _ targetType.Name, value) Catch e As InvalidCastException Console.WriteLine("Unsupported {0} --> {1} conversion.", _ cool.GetType().Name, targetType.Name) Catch e As OverflowException Console.WriteLine("{0} is out of range of the {1} type.", _ cool, targetType.Name) End Try Next End Sub End Module ' The example displays the following output: ' Converted Temperature 5.00°C to SByte 5. ' Converted Temperature 5.00°C to Int16 5. ' Converted Temperature 5.00°C to Int32 5. ' Converted Temperature 5.00°C to Int64 5. ' Converted Temperature 5.00°C to Byte 5. ' Converted Temperature 5.00°C to UInt16 5. ' Converted Temperature 5.00°C to UInt32 5. ' Converted Temperature 5.00°C to UInt64 5. ' Converted Temperature 5.00°C to Decimal 5. ' Converted Temperature 5.00°C to Single 5. ' Converted Temperature 5.00°C to Double 5. ' Converted Temperature 5.00°C to String 5,00°C.
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1