Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert from System.Array to object[] in C#

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?

like image 799
Pat Mustard Avatar asked May 21 '12 06:05

Pat Mustard


1 Answers

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);
like image 96
Jon Skeet Avatar answered Sep 19 '22 15:09

Jon Skeet