2

Can someone tell me if it is possible to pass different Arrays of Enum values to the same function.

Example:

I have two enums:

public enum FirstEnum
{ 
    FirstValue, 
    SecondValue
}    

public enum SecondEnum
{ 
    FirstValue, 
    SecondValue
}  

And I have two Arrays:

public FirstEnum[] first = new FirstEnum[]{ FirstEnum.FirstValue,
                                            FirstEnum.FirstValue,
                                            FirstEnum.SecondValue };

public SecondEnum[] second = new SecondEnum[]{SecondEnum.FirstValue,
                                              SecondEnum.SecondValue,
                                              SecondEnum.SecondValue }

Now I like to have a function that works with that:

public void WorkWithEnums(Enum[] myEnumValues)
{
   // ....    
}

and I like to pass my Arrays to this function like that:

WorkWithEnums(first);
WorkWithEnums(second);

But somehow it doesn't work. Also does not if I try with object[] instead of Enum[]

Any Ideas?

Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
Neo
  • 33
  • 2
  • whats the error you are getting? – Vajura Oct 20 '14 at 12:44
  • The error that i have is that the call has some invalid arguments. What i like to do is to figureout that values of the array. I will be also happy with a suggestion how to convert 'first' and 'second' to a string array. Something like: 'FirstValue' 'FirstValue' 'SecondValue' but this for both enums. The goal is to send the values to the same function. – Neo Oct 20 '14 at 12:51

2 Answers2

1

Your code doesn't work because covariance is not supported for value types (enums are value types).

So you could use:

WorkWithEnums(first.Cast<Enum>().ToArray())
ken2k
  • 48,145
  • 10
  • 116
  • 176
0

I would propose to make generic method working with "enum T". For example, see answer of this question: Can you loop through all enum values?

And anyway, primary influencer here is your use-case. What scenario expected inside WorkWithEnums() method?

Community
  • 1
  • 1
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42