0

I've a function wich Converts a Object to a Object Array.

I know I can do this

new [] {obj}

but then the Array is of Type object[]. I want that the Array is of the Type of whatever obj.GetType() returns!

Is this possible in a performant way?

Jochen Kühner
  • 1,385
  • 2
  • 18
  • 43

2 Answers2

1

You can use a static method of the Array class.

See http://msdn.microsoft.com/en-us/library/zb3cfh7k.aspx

The full example could be

object o = ...;// Some object you want to convert into a an array
var arrayVar = Array.CreateInstance(o.GetType(), 1);
Dirk Huber
  • 902
  • 6
  • 12
1
T[] ToObjectArray<T>(T item)
{
    return new T[] { item };
}

You can use it like

int[] arr1 = ToObjectArray(5);
Color[] arr2 = ToObjectArray(Color.Red);
L.B
  • 114,136
  • 19
  • 178
  • 224
  • It will return an array of type item is seen as by compiler, not the one it actually is (the one returned by `obj.GetType`). Unless you use `dynamic`. – MarcinJuraszek Jan 25 '14 at 22:03