Monday, January 30, 2012

Best Extension Methods: Type Conversion

Using below extension method you can convert one type to another type.
 public static T To(this object input) where T : IConvertible
    {
        string type = typeof(T).Name;

        TypeCode typecode;
        if (!Enum.TryParse(type, out typecode)) throw new ArgumentException("Could not convert!");

        return (T)Convert.ChangeType(input, typecode);
    }

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates