While writing a data loading routine in C# with .NET 2.0, I came across an apparent bug which prevented this method from converting a nullable type. A bit of Googling turned up a post by my brother Peter about this issue and a possible workaround.
I took his solution a step further and basically wrote my own ChangeType method which properly handles nullable types. I then got in touch with Peter about my solution and he suggested a better way of detecting the nullable type (I was just using a regex at first). Anyway, the end result is listed below.
In case you’re wondering why I check for a null value only after I determine that conversionType is nullable, it’s because I want the final Convert.ChangeType to throw the exception when conversionType can’t accept a null value, rather than causing the exception to be thrown in the caller.
public object ChangeType(object value, Type conversionType)
{
if ( conversionType.IsGenericType &&
conversionType.GetGenericTypeDefinition( ).Equals( typeof( Nullable<> ) ) ) {
if(value == null)
return null;
System.ComponentModel.NullableConverter nullableConverter
= new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(value, conversionType);
}



Akber Ali | 25-Mar-07 at 12:06 am | Permalink
well I spend some time to do this conversion i.e. from nullable datetime to datetime, and I consistantly had type conversion error which was solved by casting.
(DateTime)Convert.ChangeType(value, conversionType);
Could you explain why.
thanks