We all know the Convert.ChangeType() for changing a value from one (unknown) type to another (unknown) type at runtime, but this method doesn’t handle nullables and enums very well.

What may seem a simple task isn’t that simple after all. You have to differentiate nullables, value types and enums. I threw in a little recursion, and I came up with this:

public static object ConvertType(object value, Type targetType)
{
   if (value == null)
      return null;

   if (value.GetType() == targetType)
      return value;

   if (targetType.IsValueType)
   {
      if (!targetType.IsGenericType)
      {
         if (targetType.IsEnum)
            return Enum.ToObject(targetType, value);
         else
            return Convert.ChangeType(value, targetType);
      }

      if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
      {
         Type realType = targetType.GetGenericArguments()[0];

         return ConvertType(value, realType);
      }
   }

   return Convert.ChangeType(value,targetType);}

This method will do all conversions correctly, but it will return null if you pass null for a value type. This can be fixed with an extra if() check, but I thought it wasn’t necessary.

The best use for this method is for converting values read from a database to a variable that is compatible with the database type, but not exactly the same.

Share this article:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • DotNetKicks
  • DZone
  • LinkedIn
  • Reddit
  • Tumblr