C# Convert ChangeType(Object, TypeCode)
Description
Convert ChangeType(Object, TypeCode)
returns an object
of the specified type whose value is equivalent to the specified object.
Syntax
Convert.ChangeType(Object, TypeCode)
has the following syntax.
public static Object ChangeType(
Object value,
TypeCode typeCode
)
Parameters
Convert.ChangeType(Object, TypeCode)
has the following parameters.
value
- An object that implements the IConvertible interface.typeCode
- The type of object to return.
Returns
Convert.ChangeType(Object, TypeCode)
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 illustrates how to use the ChangeType(Object, TypeCode) method to change an Object to the type specified by the TypeCode parameter, if possible.
using System;// w w w. ja va 2 s . c om
public class ChangeTypeTest {
public static void Main() {
Double d = -2.345;
int i = (int)Convert.ChangeType(d, TypeCode.Int32);
Console.WriteLine("The Double {0} when converted to an Int32 is {1}", d, i);
string s = "12/12/2014";
DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));
Console.WriteLine("The String {0} when converted to a Date is {1}", s, dt);
}
}
The code above generates the following result.