Question

I have an array of objects (object[]). All the items in this array have the same type (unknown at compile time). I need to convert this array in a typed array, that is, if the items are integers, I want to get an int[].

I've looked into the Array.ConvertAll method, but I need to specify a specific type in the template, meaning that I have to get the element type then call ConvertAll for each case possible.

I've also looked into the keyword dynamic with no more luck (looks like dynamic[] is the same as object[]).

How can I achieve this?

Was it helpful?

Solution 2

Similar to Jon's solution you can do without dynamic and make use of the Array type:

public Array Convert(Array a) {
  if (a.GetLength(0) == 0){
    return new int[0];
  }
  var type = a.GetValue(0).GetType();
  var result = Array.CreateInstance(type, a.GetLength(0));
  for (int i = 0; i < a.GetLength(0); i++) {
    result.SetValue(a.GetValue(i), i);
  }
  return result;
}

OTHER TIPS

It sounds like you want something like:

dynamic array = Array.CreateInstance(input[0].GetType(), input.Length);
for (int i = 0; i < input.Length; i++)
{
    array[i] = (dynamic) input[i];
}

Here the dynamic just handles the conversion part for you.

Alternatively:

public static Array ConvertArray(object[] input)
{
    dynamic sample = input[0]; // Just used for type inference
    return ConvertArrayImpl(sample, input);
}

private static T[] ConvertArrayImpl<T>(T sample, object[] input)
{
    return input.Cast<T>().ToArray();
}

You could do make the ConvertArrayImpl call with reflection manually of course, instead of using dynamic typing.

Also note that all of these will fail if the input array is empty...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top