Tuesday, July 08, 2008

A generic ChangeType method which works with nullable conversion types

I slightly modified Peter Johnson's code which allows to use Convert.ChangeType with nullable conversion types.
To compare Conversion using TypeConverter vs. Convert.ChangeType / IConvertible see https://docs.microsoft.com/en-us/dotnet/standard/base-types/type-conversion#the-typeconverter-class

    public static class ConversionExtensions
    {
        public static T ChangeType(object value)
        {
            Type conversionType = typeof(T);
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                if (value == null)
                {
                    return default(T);
                }

                conversionType = Nullable.GetUnderlyingType(conversionType);
                if (conversionType == null) throw new Exception("ConversionExtensions ChangeType(object value) error.");
            }

            return (T) Convert.ChangeType(value, conversionType);
        }
    }
}