Why can't an array of enum be used for params Enum[]?

Viewed 132

It seems that for integer, I can either pass an array or comma-separated integers. But for enum, only comma-separated enums work. Why is it so?

    enum Animal { Dog, Cat, Mouse};
    void Caller()
    {
        int[] aaa = { 1, 2, 3 };
        Ints(1, 2, 3);
        Ints(aaa);

        Animal[] bbb = { Animal.Dog, Animal.Cat, Animal.Mouse };
        Enums(Animal.Dog, Animal.Cat, Animal.Mouse);
        //CS1503 Argument 1: cannot convert from 'Animal[]' to 'System.Enum'
        Enums(bbb);
    }

    void Ints(params int[] aaa)
    {
    }

    void Enums(params Enum[] aaa)
    {
    }
3 Answers

The problem is that Enum isn't a "real" type that describes an enum, because the former is a class and the latter is a plain old integer of some kind (you can describe which kind of integer you want). More accurately, Enum is an enum boxed.

Note that you can still get full functionality, while keeping your function generic, if you let the compiler construct the correct generic array type:

void Enums<TEnum>(params TEnum[] aaa) where TEnum: Enum
{
}

Short answer is:

Because, any enumeration inherit from Enum, but arrays are covariant, but only for classes, which enums are not. So Animal[] does not inherit from Enum[]

So, passing enums "argument by argument" leverages inheritance to make the code compile.

Animal is the type of your enum. The corrected function:

void Enums(params Animal [] aaa)
{
}
Related