How to cast a object to IList<T> with unknown type T
See the question and my original answer on StackOverflowIf you just need the object from an enumerable, at a given index, here is a simple function that does it:
public static object GetObjectAt(IEnumerable enumerable, int index)
{
int i = 0;
foreach (object obj in enumerable)
{
if (i == index)
return obj;
i++;
}
throw new IndexOutOfRangeException();
}
And in your case, you would do this:
object oo = GetObjectAt((IEnumerable)(WeakReference)vals[2], (int)vals[4]);
Of course there are alternatives that look more sexy (see other answers), with fancy linq queries and cool C# 4 dynamic new trendy stuff :-) but, in general, if you don't "need" the T type (in your example code, you don't need it), you don't need generics. This solution is actually supported with any .NET Framework and C# versions, from 1 to 4.