Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
I was working with a ORM system the other day and kept running into problems with the Nullable types when I called Convert.ChangeType().
[InvalidCastException: Invalid cast from 'System.DateTime' to ' System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
A Quick Google search came up with a number of entries. This is a known problem in the CLR.
Here a couple or other blogs on this and below is my version of the code:
Peter Johnson's BlogThe PumaCode.org Blog
public static object ChangeType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return null; NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } if (conversionType.IsEnum) return Enum.ToObject(conversionType, value); else return Convert.ChangeType(value, conversionType); }