bnieland
bnieland

Reputation: 6516

convert an array of enums into a generic array of enums

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.

Upvotes: 1

Views: 1714

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

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;

Upvotes: 3

daryal
daryal

Reputation: 14929

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];                
}

Upvotes: 0

Related Questions