+6  A: 

I think the Enum.ToObject method will do what you want.

Type type= typeof(Foo);
object o1 = Enum.ToObject(type,GetValue());
aaronb
Marc Gravell
+2  A: 

Just wanted to add something to @aaronb's answer: I had to do this very thing for some auto-mapping code and found out that I needed to do several checks in order to make the code work for arbitrary types. In particular, null values and nullable enums will give you headaches.

The most foolproof code I have at the moment is this:

static object CastBoxedValue(object value, Type destType)
{
    if (value == null)
        return value;

    Type enumType = GetEnumType(destType);
    if (enumType != null)
        return Enum.ToObject(enumType, value);

    return value;
}

private static Type GetEnumType(Type type)
{
    if (type.IsEnum)
        return type;

    if (type.IsGenericType)
    {
        var genericDef = type.GetGenericTypeDefinition();
        if (genericDef == typeof(Nullable<>))
        {
            var genericArgs = type.GetGenericArguments();
            return (genericArgs[0].IsEnum) ? genericArgs[0] : null;
        }
    }
    return null;
}

If you can never have a nullable type then just ignore this. :)

Aaronaught
Valuable thoughts, but indeed I've already stripped out things like `Nullable<T>`, `List<T>` etc upstream of this.
Marc Gravell