Convert.ChangeType Wrapper that Handles Nullable Types

A known problem with the useful late-bound casting method Convert.ChangeType is that it doesn’t handle nullable types. I discovered this problem several months ago, talked to the CLR team at Microsoft about it, blogged about it, and have now written and tested a wrapper method that does handle nullable types. Hopefully, a future .NET Framework service pack will include this functionality, so this method can be deleted and calls to it can be changed to call Convert.ChangeType directly again.

public static object ChangeType(object value, Type conversionType)
// Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
// checking properties on conversionType below.
if (conversionType == null)
throw new ArgumentNullException("conversionType");
} // end if

// If it's not a nullable type, just pass through the parameters to Convert.ChangeType

if (conversionType.IsGenericType &&
// It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
// InvalidCastException (per,
// determine what the underlying type is
// If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
// have a type--so just return null
// Note: We only do this check if we're converting to a nullable type, since doing it outside
// would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
// value is null and conversionType is a value type.
if (value == null)
return null;
} // end if

// It's a nullable type, and not null, so that means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
} // end if

// Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
// nullable type), pass the call on to Convert.ChangeType
return Convert.ChangeType(value, conversionType);


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: