I have a following problem:
- I need to store generic objects with different type parameters, something like javish
Sth<A,?>, - “?” types are usually primitives, so not really expandable/changeable
- I need to execute some methods on each element of my list
- different methods for different types, or at least different overloads of these methods
While I don’t know how to store such types, let’s assume List<object> for simplicity.
I could store the type in question somewhere (List<KeyValuePair<Type,object>>), getting it with typeof(), but then, how can I cast my object back to the required type?
Something like
foreach(var entry in myList)
{
var obj = (Sth<A, entry.Key>) entry.Value;
myMethod(obj); //This can have overloads for object, Sth<A,int>, Sth<A,string>,
// etc. Generally, I need a correct type of obj here.
}
Of course myMethod<T> is a generic library method with too many overloads to if-else it with obj is Sth<A, uint>…
I think I could create a new object based on entry.Key and then fill
Are such combinations with types even possible?
I believe, that the answer lies in proper creation of myList, but I don’t know how to do it.
Any help would be appreciated!
Merry xmas 🙂
If you’re using C# 4, you can use
dynamicfor this:The overload resolution will now be performed at execution time based on the execution-time type of
value.