Many times you find yourself having to convert the type of an object to another. The ToString() method is probably one of the most useful methods, it's great for easy conversion of objects to string, but what if you want to do it the other way round or even an int to a decimal?

Say I had a string and I wanted it to turn it into an Int32, I could just use the Convert class and do a Convert.ToInt32(myInt) but I would like to be able to do this myInt.ToInt32().

Well now you can with .NET 3.5 Extension Methods! Here's my implementation

public static T To<T>(this IConvertible s)
{
    return (T)Convert.ChangeType(s, typeof(T));
}


All objects that inherit from an IConvertible e.g. string, int, bool etc., will convert the value to the type you specify e.g.

int myInt = myInt.To<Int32>();


It works perfectly with the Visual Studio Intellisense 


kick it on DotNetKicks.com