tsimbalar
tsimbalar

Reputation: 6000

What is the "general" type for an array of enum?

I have a method that would like to take as parameter an array of Custom Enum types.

Something that would look like this:

public void DoSomething(WhatDoIPutHere[] parameters)

I would like to pass to this method either a Enum1[] or a Enum2[] where Enum1 and Enum2 are 2 Enum types.

What do I need to use instead of WhatDoIPutHere ?

I would have expected to define the signature of DoSomething as Enum[] as somehow Enum is the base class for Enum types (right?) :

public void DoSomething(Enum[] parameters)

but it gives a :

cannot convert from 'xxx.Enum1[]' to 'System.Enum[]'

I also tried defining it as object[] but I get the same kind of compiler error..

I know this is totally smelly code, and if I could I would definitely get rid of it ...

Upvotes: 3

Views: 361

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503799

You can't. Value type arrays aren't covariant. You sort of want to write:

public void DoSomething<T>(T[] parameters) where T : struct, System.Enum

... but that's not allowed either (type parameters can't be constrained to be enums or delegates).

Options:

  • Allow any array:

    public void DoSomething(Array parameters)
    
  • Allow any array of value types:

    public void DoSomething<T>(T[] parameters)
    
  • Use Unconstrained Melody to write the first form, via IL-rewriting hack.

Upvotes: 6

Related Questions