Piotr Zierhoffer
Piotr Zierhoffer

Reputation: 5151

List of different generic types, dynamic casting

I have a following problem:

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 :)

Upvotes: 0

Views: 547

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503749

If you're using C# 4, you can use dynamic for this:

foreach (KeyValuePair<A, object> entry in myList)
{
    dynamic value = entry.Value;
    myMethod(value);
}

The overload resolution will now be performed at execution time based on the execution-time type of value.

Upvotes: 6

Related Questions