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
{
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
}
return (T) Convert.ChangeType(value, conversionType);
}
}
}
Tuesday, July 08, 2008
A generic ChangeType method which works with nullable conversion types
Comments for this post
All comments