0

We already know we can convert an enum to another type of enum, so the following compiles:

public class EnumTest
{
   enum Enum1 { Foo };
   enum Enum2 { Foo };
   void Test () 
   {
       System.Enum e = new Enum2();   // compiles
       Enum1 e1 = (Enum1)new Enum2(); // compiles with an explicit cast
   }
}

But this doesn't compile:

public class EnumTest
{
   enum Enum1 { Foo };
   enum Enum2 { Foo };
   void Test () 
   {
       List<System.Enum> eList = new List<Enum2>();         // doesn't compile
       List<Enum1> e1List = (List<Enum1>)new List<Enum2>(); // doesn't compile
   }
}

Is that a covariance issue? If not, is there a way to make it work?

OfirD
  • 7,020
  • 2
  • 33
  • 68
  • Are you expecting `Enum1,Foo` to always equate to `Enum2.Foo`? What if `Enum1.Foo` is equal to integer 1 and `Enum2.Foo` is equal to integer 2? – DavidG Jul 12 '18 at 13:50

2 Answers2

2

It's not a co-variance issue, it's a variance issue. Enums are value types and co-variance is not supported for value types. And List<T> is a class, not an interface or delegate. Co-variance is only supported for interfaces and delegates.

You have to cast/convert the elements in the lists:

List<Enum2> list2 = ...
List<System.Enum> eList = list2.Cast<System.Enum>().ToList();

But this of course results in a new list. eList is a different instance than list2.

René Vogt
  • 41,709
  • 14
  • 73
  • 93
2

You can't cast like that, Enum1 and Enum2 are completely different things. You can do it with some simple Linq though. For example:

List<Enum2> eList = new List<Enum2>
{ 
    Enum2.Foo 
};

List<Enum1> e1List = eList
    .Select(x => (Enum1)x)
    .ToList();

Note this is using a straight case, but you might want to use the conversion function from the question you linked.

DavidG
  • 104,599
  • 10
  • 205
  • 202