I have a list of enums that i filled, and for many reason i casted it to an object ob. A function receive this object and try to parse it as a generic Enum.
List<MyEnum> mList = new List<MyEnum>();
// i fill my list
mList.Add(MyEnum.FirstValue);
//...
object ob = mList;
if (ob.GetType().IsGenericType && ob.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
Type subTypeOb = ob.GetType().GenericTypeArguments.Single();
if (subTypeOb.IsEnum)
{
foreach (Enum subOb in (List<Enum>)ob)
{
// do stuff
}
}
}
The thing is, i want to cast it back to a generic List of Enum so that i can use it. I don't want and don't need to cast it back to it's original enum (it can be many other enum).
But i alwais get an error on: (List<Enum>)ob
:
can't cast object 'System.Collections.Generic.List
1[MyEnum]' en type 'System.Collections.Generic.List
1[System.Enum]'
I can't cast it to a List, i can't find a way to cast it in a list of anything generic. What i don't understand is : between a generic Enum and MyEnum, there isn't a lot of difference, it's the same memory space.
Could you help me figure out?
---- EDIT --- More Infos
Oh god i'm so stupid, i forgot to :using System.Collections;
Now i can do : List<Enum> enums = (ob as IList).Cast<Enum>().ToList();
And it work perfectly fine ! Thanks you stranger.