Re: Dynamically determine and cast type

Marc Brooks <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.clr
Message-ID <[email protected]>
From WilsonORMapper's QueryHelper class (this supports a ton more
conversions than Convert.ChangeType and goes from object)... Use the
return value in the property SetValue method call.

/// <summary>
/// Convert a value to another type -- supports Nullable types, unlike
Convert.ChangeType.
/// </summary>
/// <param name="value">Value to be converted -- must be a value type.</param>
/// <param name="type">Type to convert value to -- must be a value type.</param>
/// <returns></returns>
static public object ChangeType(object value, Type type)
{
  if (value == null && type.IsGenericType)
    return Activator.CreateInstance(type);

  if (value == null)
    return null;

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

  if (type.IsEnum)
  {
    if (value is string)
      return Enum.Parse (type, value as string); // RTS/GOP
    else
      return Enum.ToObject(type, value);
  }

  if (type.IsGenericType
      && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    return Convert.ChangeType(value, Nullable.GetUnderlyingType(type));

  if (!type.IsInterface && type.IsGenericType)
  {
    Type innerType = type.GetGenericArguments()[0];
    object innerValue = QueryHelper.ChangeType(value, innerType); // recurse!
    return Activator.CreateInstance(type, new object[] { innerValue });
  }

  if (value is string && type == typeof(Guid))
    return new Guid(value as string);

  if (value is string && type == typeof(Version))
    return new Version(value as string);

  if (value is IConvertible)
    return Convert.ChangeType(value, type);
  else
    return value;
}


-- 
"He uses statistics as a drunken man uses lamp-posts… for support
rather than illumination." Andrew Lang

Marc C. Brooks
http://musingmarc.blogspot.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.