I have a class (A web control) that has a property of type IEnumerable and would like to work with the parameter using LINQ.
Is there any way to cast / convert / invoke via reflection to IEnumerable<T> not knowing the type at compile time?
Method void (IEnumerable source)
{
var enumerator = source.GetEnumerator();
if (enumerator.MoveNext())
{
var type = enumerator.Current.GetType();
Method2<type>(source); // this doesn't work! I know!
}
}
void Method2<T>(IEnumerable<T> source) {}
Does your
Method2really care what type it gets? If not, you could just callCast<object>():If you definitely need to get the right type, you’ll need to use reflection.
Something like:
It’s not ideal though… in particular, if source isn’t exactly an
IEnumerable<type>then the invocation will fail. For instance, if the first element happens to be a string, but source is aList<object>, you’ll have problems.