I have a object[] containig some values. I want to extract infomation out of it, but I fail at casting the second object in the array (a WeakReference) to a IList with T as the third value in the array.
Take a look at my code:
object[] vals = GetValues(); //vals[2] = WeakReference, vals[3] = Type of T, vals[4] = index in the list
IList<((Type)vals[3])> list = (IList<((Type)vals[3])>)(((WeakReference)vals[2]).Target); //This line does not even compile, seems like I'm doing something wrong..
object oo = list.ElementAt((int)vals[4]);
//Do something with oo...
Any suggestions how I can cast the Target of the WeakReference to a IList interface with T = vals[3] ?
It’s really strange that you are packing so much heterogeneous information into an array. Arrays are normally used to store elements of the same type. Why not encapsulate the data in a proper type?
But to answer the question as asked – in C# 4, you can use
dynamic:(EDIT: If you want to minimize the use of
dynamichere, cast to aWeakReferenceand leave the dynamic call to the end. This way, type-safety is ‘maximized’.)Otherwise, you can use reflection:
(EDIT: If the indexer could be explicitly implemented, you’ll probably need to use the interface mappings.)