1

How can I convert an array of enums into a generic array of enums in c#.

To be clear:

Given:

public enum PrimaryColor
{
    red = 0,
    blue = 1,
    yellow = 3
}

public enum SecondaryColor
{
    green = 0,
    purple = 1,
    orange = 2
}

I want to do something like this:

public class MyClass
{
    public static void Main()
    {
        PrimaryColor[] pca = {PrimaryColor.blue, PrimaryColor.yellow};
        SecondaryColor[] sca = {SecondaryColor.purple, SecondaryColor.orange};

        Enum[] enumArray = pca;
    }

}

which leads to a compiler error of:

Cannot implicitly convert type 'PrimaryColor[]' to 'System.Enum[]'

I could use linq or some more iterative process, but I wonder if there is a better cast I could use instead.

1

2 Answers 2

3

You can do it iteratively only

Enum[] enumArray = Array.ConvertAll(pca, item => (Enum)item);

Or (less efficient but Linq!)

Enum[] enumArray = pca.Cast<Enum>().ToArray();

Why you can't simply cast arrays? Because in C# covariance enabled only for arrays of reference types (enums are value types). So, with class Foo you can do:

Foo[] foos = new Foo[10];
object[] array = (object[])foos;
Sign up to request clarification or add additional context in comments.

4 Comments

An interesting oddity in the type system is that the CLR type system allows array covariance on compatible value types. For example, uint[] is convertible to int[]. C# as you correctly note only allows array covariance if both types are reference types. Which means that it is possible that in C#, the cast (int[])(object)x will succeed at runtime, but the same cast without object would fail at compile time.
@EricLippert thanks, great comment! Didn't know that array covariance on compatible value types is allowed. Btw why Enum does not considered compatible for example above? I.e. I can do (int[])(object)pca, but I can't do (Enum[])(object)pca. Also looks like there is a bug in VS2012 s4.postimage.org/c17b94me5/array_covariance.png :)
Enum is a reference type; it's a boxed enum. The array therefore has to be full of references, not full of values.
See blogs.msdn.com/b/ericlippert/archive/2009/09/24/… and stackoverflow.com/questions/1178973/… for more details on how CLR variance differs from C# variance.
0
PrimaryColor[] pca = { PrimaryColor.blue, PrimaryColor.yellow };
SecondaryColor[] sca = { SecondaryColor.purple, SecondaryColor.orange };

Enum[] enumArray = pca.Select(q => q as Enum).ToArray();

Or;

for (int i=0; i<pca.Count();i++)
{
    enumArray[i] = pca[i];                
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.