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:

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

conversionType = Nullable.GetUnderlyingType(conversionType); ;
}

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