Back in 2006 Peter Johnson discovered .NET 2.0′s Convert.ChangeType didn’t support nullable types.  He wrote a nice wrapper to help out.  To make it a little more “3.5″ I figured it deserved an extension method (note you’ll need Peter’s code too):

    public static class ExtensionMethods
    {
        public static T ChangeType<T>( this object value )
        {
            return (T)ChangeType( value, typeof( T ) );
        }
    }

In addition I tweaked Peter’s code slightly to make his non-generic ChangeType an extension method too (note I removed the comments here for brevity; you should get Peter’s code instead as it’s more readable):

    public static object ChangeType( this object value, Type conversionType )
    {
        if ( conversionType == null )
        {
            throw new ArgumentNullException( "conversionType" );
        }

        if ( conversionType.IsGenericType &&
          conversionType.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) )
        {
            if ( value == null ) return null;

            NullableConverter nullableConverter = new NullableConverter( conversionType );
            conversionType = nullableConverter.UnderlyingType;
        }

        return Convert.ChangeType( value, conversionType );
    }

Now you can be really lazy with code like this:

    var myInt = myStringOrWhatever.ChangeType<int>();

    int myOther = myStringOrWhatever.ChangeType( typeof( int ) );

    Type myType = ...;
    object myTypedThing = myStringOrWhatever.ChangeType( myType );

If you’ll always know the type you’re converting to at compile time, you might prefer to use the conversion methods in System.ComponentModel such as DecimalConverter.

About these ads