C# Convert ChangeType(Object, TypeCode, IFormatProvider)
Description
Convert ChangeType(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.
Syntax
Convert.ChangeType(Object, TypeCode, IFormatProvider)
has the following syntax.
public static Object ChangeType(
Object value,//w ww .j av a 2 s.c o m
TypeCode typeCode,
IFormatProvider provider
)
Parameters
Convert.ChangeType(Object, TypeCode, IFormatProvider)
has the following parameters.
value
- An object that implements the IConvertible interface.typeCode
- The type of object to return.provider
- An object that supplies culture-specific formatting information.
Returns
Convert.ChangeType(Object, TypeCode, IFormatProvider)
method returns 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.
Example
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.
/*from w ww.jav a2 s . c om*/
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();
foreach (object value in values)
{
foreach (TypeCode enumType in ((TypeCode[]) Enum.GetValues(typeof(TypeCode))))
{
try {
Console.WriteLine("{0} ({1}) --> {2} ({3}).",
value, value.GetType().Name,
Convert.ChangeType(value, enumType, provider),
enumType.ToString());
}
catch (Exception) {
Console.WriteLine("Exception");
}
}
}
}
}
The code above generates the following result.