ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

To

converts one type to another

Source

public static T To<T>(this IConvertible value)
{
    try
    {
        return (T) Convert.ChangeType(value, typeof (T));
    }
    catch
    {
        return default(T);
    }
}

Example

var age = "28";
var intAge = age.To<int>();
var doubleAge = intAge.To<double>();
var decimalAge = doubleAge.To<decimal>();

Author: Márcio Fábio Althmann

Submitted on: 9 nov. 2011

Language: C#

Type: System.IConvertible

Views: 4996