C# Convert ChangeType(Object, Type, IFormatProvider)
Description
Convert ChangeType(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.
Syntax
Convert.ChangeType(Object, Type, IFormatProvider)
has the following syntax.
public static Object ChangeType(
Object value,/*from w w w.java 2 s . c o m*/
Type conversionType,
IFormatProvider provider
)
Parameters
Convert.ChangeType(Object, Type, IFormatProvider)
has the following parameters.
value
- An object that implements the IConvertible interface.conversionType
- The type of object to return.provider
- An object that supplies culture-specific formatting information.
Returns
Convert.ChangeType(Object, Type, IFormatProvider)
method returns 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.
Example
The following example illustrates the conversion to and from a Continent enumeration value.
/*from ww w .ja va 2 s . co m*/
using System;
using System.Globalization;
public enum Continent
{
Africa, Antarctica, Asia, Australia, Europe,
NorthAmerica, SouthAmerica
};
public class Example
{
public static void Main()
{
CultureInfo provider = new CultureInfo("fr-FR");
// Convert a Continent to a Double.
Continent cont = Continent.NorthAmerica;
Console.WriteLine("{0:N2}",
Convert.ChangeType(cont, typeof(Double),provider));
// Convert a Double to a Continent.
Double number = 6.0;
try {
Console.WriteLine("{0}",
Convert.ChangeType(number, typeof(Continent),provider));
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Double to a Continent");
}
Console.WriteLine("{0}", (Continent) number);
}
}
The code above generates the following result.