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?
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?
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);
T[] ToObjectArray<T>(T item)
{
return new T[] { item };
}
You can use it like
int[] arr1 = ToObjectArray(5);
Color[] arr2 = ToObjectArray(Color.Red);