Reputation: 4339
I have a List<object>
that I want to cast to a strongly typed array. The problem is that I don't know the list type at compile time, as it can be one of many objects.
Essentially if I have Type objectType = list[0].GetType()
I want to be able to call list.Cast<objectType>().ToArray()
.
How can I do this? I tried using Reflection as follows:
Type listType = list[0].GetType();
MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(new Type[] { listType });
castMethod.Invoke(null, new object[] { list});
The invocation returns a CastIterator which appears to have no public methods.
Upvotes: 2
Views: 129
Reputation: 564891
You could use:
MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(new Type[] { listType });
object castIterator = castMethod.Invoke(null, new object[] { list});
var toArrayMethod = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public);
toArrayMethod = toArrayMethod.MakeGenericMethod(new Type[] { listType });
object theArray = toArrayMethod.Invoke(null, new[] {castIterator});
At the end of this, theArray
will be an array that's strongly typed.
Upvotes: 4