Export (0) Print
Expand All

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.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static Object ChangeType(
	Object value,
	Type conversionType,
	IFormatProvider provider
)

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.Object
An 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.

ExceptionCondition
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:

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.

using System;

public enum Continent
{
   Africa, Antarctica, Asia, Australia, Europe, 
   NorthAmerica, SouthAmerica
};

public class Example
{
   public static void Main()
   {
      // Convert a Continent to a Double.
      Continent cont = Continent.NorthAmerica;
      Console.WriteLine("{0:N2}", 
                        Convert.ChangeType(cont, typeof(Double)));

      // Convert a Double to a Continent.
      Double number = 6.0;
      try {
         Console.WriteLine("{0}", 
                           Convert.ChangeType(number, typeof(Continent)));
      }
      catch (InvalidCastException) {
         Console.WriteLine("Cannot convert a Double to a Continent");
      }

      Console.WriteLine("{0}", (Continent) number);   
   }
}
// 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<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.

using System;

public class Example
{
   public static void Main()
   {
      int? intValue1 = 12893;
      double dValue1 = (double) Convert.ChangeType(intValue1, typeof(Double), null);
      Console.WriteLine("{0} ({1})--> {2} ({3})", intValue1, intValue1.GetType().Name,
                        dValue1, dValue1.GetType().Name);


      float fValue1 = 16.3478f;
      int? intValue2 = (int) fValue1; 
      Console.WriteLine("{0} ({1})--> {2} ({3})", fValue1, fValue1.GetType().Name,
                        intValue2, intValue2.GetType().Name);
   }
}
// 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.

using System;
using System.Globalization;

public class Temperature : IConvertible
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   {
      get { return this.m_Temp; }   
   }

   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }    
   }

   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) (this.m_Temp * 9 / 5 + 32), 2); }
   }

   public override string ToString()
   {
      return m_Temp.ToString("N2") + "°C";
   }

   // IConvertible implementations. 
   public TypeCode GetTypeCode()
   {
      return TypeCode.Object;
   }

   public bool ToBoolean(IFormatProvider provider) 
   {
      if (m_Temp == 0)
         return false;
      else 
         return true;
   } 

   public byte ToByte(IFormatProvider provider)
   {
      if (m_Temp < Byte.MinValue || m_Temp > Byte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.", 
                                                   this.m_Temp));
      else 
         return Decimal.ToByte(this.m_Temp);
   }

   public char ToChar(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to Char conversion is not supported.");
   } 

   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to DateTime conversion is not supported.");
   }

   public decimal ToDecimal(IFormatProvider provider)
   {
      return this.m_Temp;
   }

   public double ToDouble(IFormatProvider provider)
   {
      return Decimal.ToDouble(this.m_Temp);
   }   

   public short ToInt16(IFormatProvider provider)
   {
      if (this.m_Temp < Int16.MinValue || this.m_Temp > Int16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int16 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToInt16(this.m_Temp);
   }

   public int ToInt32(IFormatProvider provider)
      {
      if (this.m_Temp < Int32.MinValue || this.m_Temp > Int32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int32 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToInt32(this.m_Temp);
   }

   public long ToInt64(IFormatProvider provider)
   {
      if (this.m_Temp < Int64.MinValue || this.m_Temp > Int64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int64 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToInt64(this.m_Temp);
   }

   public sbyte ToSByte(IFormatProvider provider)
   {
      if (this.m_Temp < SByte.MinValue || this.m_Temp > SByte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the SByte type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToSByte(this.m_Temp);
   }

   public float ToSingle(IFormatProvider provider)
   {
      return Decimal.ToSingle(this.m_Temp);
   }

   public string ToString(IFormatProvider provider)
   {
      return m_Temp.ToString("N2", provider) + "°C";
   }

   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean: 
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(Temperature).Equals(conversionType))
               return this;
            else 
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.",
                                                            conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(provider);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);   
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));   
      }
   }

   public ushort ToUInt16(IFormatProvider provider)
   {
      if (this.m_Temp < UInt16.MinValue || this.m_Temp > UInt16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt16 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToUInt16(this.m_Temp);
   }

   public uint ToUInt32(IFormatProvider provider)
   {
      if (this.m_Temp < UInt32.MinValue || this.m_Temp > UInt32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt32 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToUInt32(this.m_Temp);
   }

   public ulong ToUInt64(IFormatProvider provider)
   {
      if (this.m_Temp < UInt64.MinValue || this.m_Temp > UInt64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt64 type.",
                                                   this.m_Temp));
      else 
         return Decimal.ToUInt64(this.m_Temp);
   }
}

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.

public class Example
{
   public static void Main()
   {
      Temperature cool = new Temperature(5);
      Type[] targetTypes = { typeof(SByte), typeof(Int16), typeof(Int32),
                             typeof(Int64), typeof(Byte), typeof(UInt16),
                             typeof(UInt32), typeof(UInt64), typeof(Decimal),
                             typeof(Single), typeof(Double), typeof(String) };
      CultureInfo provider = new CultureInfo("fr-FR");

      foreach (Type targetType in targetTypes)
      {
         try {
            object value = Convert.ChangeType(cool, targetType, provider);
            Console.WriteLine("Converted {0} {1} to {2} {3}.",
                              cool.GetType().Name, cool.ToString(),
                              targetType.Name, value);
         }
         catch (InvalidCastException) {
            Console.WriteLine("Unsupported {0} --> {1} conversion.",
                              cool.GetType().Name, targetType.Name);
         }                     
         catch (OverflowException) {
            Console.WriteLine("{0} is out of range of the {1} type.",
                              cool, targetType.Name);
         }
      }
   }
}
// The example dosplays 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.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft