Export (0) Print
Expand All

Convert.ChangeType Method (Object, TypeCode, 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,
	TypeCode typeCode,
	IFormatProvider provider
)

Parameters

value
Type: System.Object

An object that implements the IConvertible interface.

typeCode
Type: System.TypeCode

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 underlying type is typeCode and whose value is equivalent to value.
-or-
A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

ExceptionCondition
InvalidCastException

This conversion is not supported.

-or-

value is null and typeCode specifies a value type.

-or-

value does not implement the IConvertible interface.

FormatException

value is not in a format for the typeCode type recognized by provider.

OverflowException

value represents a number that is out of the range of the typeCode type.

ArgumentException

typeCode is invalid.

ChangeType(Object, TypeCode, IFormatProvider) is a general-purpose conversion method that converts the object specified by value to a predefined type specified by typeCode. The value parameter can be an object of any 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 also requires that conversion of value to typeCode be supported.

The ChangeType(Object, TypeCode, IFormatProvider) method does not support the conversion of value to a custom type. To perform such a conversion, call the ChangeType(Object, Type, IFormatProvider) method.

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 a null IFormatProvider argument is passed to these methods, the CultureInfo object that represents the current thread culture is used.

  • 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.

  • 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 value is an application-defined type, its IConvertible implementation may use the provider parameter.

The following example defines a custom format provider named InterceptProvider that indicates when its GetFormat method is called and returns a NumberFormatInfo for the fr-FR culture and a DateTimeFormatInfo object for the en-US culture. This format provider is used in all calls to the ChangeType(Object, TypeCode, IFormatProvider) method. The example then creates an array with a Double and a DateTime value and makes repeated calls to ChangeType(Object, TypeCode, IFormatProvider) with each value and each member of the TypeCode enumeration. The example illustrates when the method uses the IFormatProvider parameter and also illustrates the use of the provider parameter to perform culture-sensitive formatting.

using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(NumberFormatInfo)) {
         Console.WriteLine("   Returning a fr-FR numeric format provider.");
         return new System.Globalization.CultureInfo("fr-FR").NumberFormat;
      }   
      else if (formatType == typeof(DateTimeFormatInfo)) {
         Console.WriteLine("   Returning an en-US date/time format provider.");
         return new System.Globalization.CultureInfo("en-US").DateTimeFormat;
      }
      else {
         Console.WriteLine("   Requesting a format provider of {0}.", formatType.Name);
         return null;
      }
   }
}

public class Example
{
   public static void Main()
   {
      object[] values = { 103.5d, new DateTime(2010, 12, 26, 14, 34, 0) };
      IFormatProvider provider = new InterceptProvider();

      // Convert value to each of the types represented in TypeCode enum. 
      foreach (object value in values)
      {
         // Iterate types in TypeCode enum. 
         foreach (TypeCode enumType in ((TypeCode[]) Enum.GetValues(typeof(TypeCode))))
         {         
            if (enumType == TypeCode.DBNull || enumType == TypeCode.Empty) continue;

            try {
               Console.WriteLine("{0} ({1}) --> {2} ({3}).", 
                                 value, value.GetType().Name,
                                 Convert.ChangeType(value, enumType, provider),
                                 enumType.ToString());
            }
            catch (InvalidCastException) {
               Console.WriteLine("Cannot convert a {0} to a {1}",
                                 value.GetType().Name, enumType.ToString());
            }                     
            catch (OverflowException) {
               Console.WriteLine("Overflow: {0} is out of the range of a {1}",
                                 value, enumType.ToString());
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output: 
//    103.5 (Double) --> 103.5 (Object). 
//    103.5 (Double) --> True (Boolean). 
//    Cannot convert a Double to a Char 
//    103.5 (Double) --> 104 (SByte). 
//    103.5 (Double) --> 104 (Byte). 
//    103.5 (Double) --> 104 (Int16). 
//    103.5 (Double) --> 104 (UInt16). 
//    103.5 (Double) --> 104 (Int32). 
//    103.5 (Double) --> 104 (UInt32). 
//    103.5 (Double) --> 104 (Int64). 
//    103.5 (Double) --> 104 (UInt64). 
//    103.5 (Double) --> 103.5 (Single). 
//    103.5 (Double) --> 103.5 (Double). 
//    103.5 (Double) --> 103.5 (Decimal). 
//    Cannot convert a Double to a DateTime 
//       Returning a fr-FR numeric format provider. 
//    103.5 (Double) --> 103,5 (String). 
//     
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (Object). 
//    Cannot convert a DateTime to a Boolean 
//    Cannot convert a DateTime to a Char 
//    Cannot convert a DateTime to a SByte 
//    Cannot convert a DateTime to a Byte 
//    Cannot convert a DateTime to a Int16 
//    Cannot convert a DateTime to a UInt16 
//    Cannot convert a DateTime to a Int32 
//    Cannot convert a DateTime to a UInt32 
//    Cannot convert a DateTime to a Int64 
//    Cannot convert a DateTime to a UInt64 
//    Cannot convert a DateTime to a Single 
//    Cannot convert a DateTime to a Double 
//    Cannot convert a DateTime to a Decimal 
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (DateTime). 
//       Returning an en-US date/time format provider. 
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (String).

.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

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