Sinbadsoft/Sinbadsoft.Lib — Issue #1: Treating Nullable values in TryConvert
Author: htoma
Created: 2012-03-03 14:44:01+00:00
State: open

In order to treat nullable values on conversion, you need to get to the underlying type.
Use this snippet for the last part of TryConvert (credits to aspalliance.com):

try
{
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (sourceValue != null)
{
var nullableConverter = new NullableConverter(targetType);
targetType = nullableConverter.UnderlyingType;
}
}
targetValue = Convert.ChangeType(sourceValue, targetType);
return true;
}
catch (InvalidCastException)
{
return false;
}