So, arrayType
is the type you want to cast arrayData
to. So for example, if you pass typeof(int)
as arrayType
, you want to cast arrayData
into int[]
.
While you could do this using reflection, you don’t really get any benefit from it: The type is only known at compile time, so any conversion would only be there at compile time, so you won’t get any type safety from it, and as such couldn’t access the data.
You could only cast arrayData
to object[]
to at least get access to the array itself:
void DoSomething(object arrayData, Type arrayType)
{
object[] data = (object[])arrayData;
// do something with data
}
Alternatively, you could also create a (private) generic method that takes the data and then converts it into a typed array:
private void DoSomethingGeneric<T>(object arrayData)
{
T[] data = (T[])arrayData;
// do something with data
}
This would give you access to the type. You could call that method using reflection from the non-generic DoSomething
public void DoSomething(object arrayData, Type arrayType)
{
MethodInfo mi = this.GetType().GetMethod("DoSomethingGeneric").MakeGenericMethod(arrayType);
mi.Invoke(this, new object[] { arrayData });
}
But even with the generic method, you still have one problem: What do you want to do with that T[]
that you couldn’t do with an object[]
?