18

I have a COM function that expects object[] as a parameter:

foo(object[] values)

I want to pass some enum fields to it so I use the following:

object[] fields = (object[])Enum.GetValues(typeof(SomeEnumType));

However, when I try to pass fields to foo(...) i.e. [foo(fields)] I get an error:

"Unable to cast object of type `SomeEnumType[]' to type 'system.Object[]'.

Can anyone tell me what I'm doing wrong?

3 Answers 3

29

As the exception says, you can't convert cast a SomeEnumType[] to object[] - the former is an array where each value is a SomeEnumType value; the latter is an array where each element is a reference.

With LINQ you can create a new array easily enough:

object[] fields = Enum.GetValues(typeof(SomeEnumType))
                      .Cast<object>()
                      .ToArray();

This will basically box each element (each enum value) to create an IEnumerable<object>, then create an array from that. It's similar to Tilak's approach, but I prefer to use Cast when I don't actually need a general-purpose projection.

Alternatively:

SomeEnumType[] values = (SomeEnumType[]) Enum.GetValues(typeof(SomeEnumType));
object[] fields = Array.ConvertAll(values, x => (object) x);
Sign up to request clarification or add additional context in comments.

Comments

3
Enum.GetValues(typeof(SomeEnumType)).Cast<object>().ToArray()

2 Comments

Thanks. i missed cast in between.
... and then you just turned it into Jon Skeet's answer, without the explanation.
1

You need to cast the proper array type. Try something along these lines:

object[] fields = (object[])Enum.GetValues(typeof(SomeEnumType)).Cast<object>().ToArray();

The error message is stating that the function is expecting an object array of type "object" and you're passing in one of type "SomeEnumType", so there is a type mismatch.

2 Comments

Indeed. As Developer is hinting at, Array is an object, not a C++ style [] array.
True enough - I come from a C++ background: old habits die hard :)

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.