I’ve got an object which is a Dictionary of an unknown type (ie I don’t know the type for the key and the value)
I want to retrieve all of its values so I can access those by index.
So what I want to do is something like that :
Dictionary<object, object> d = (Dictionary<object, object>)obj; // cast error
l = new List<KeyValuePair<object,object>>();
foreach (KeyValuePair<object, object> k in d)
l.Add(new KeyValuePair<object,object>(k.Key, k.Value));
However, as expected, the runtime won’t let me cast to a Dictionary< object, object>.
Is there a way to do this in .net 3.0 ? (for example using reflection?)
You can’t cast
objto aDictionary<object, object>because it isn’t aDictionary<object, object>. Yes, its keys and values derive fromobject, and can be thus cast toobject. But you can’t cast generic types in C# because they aren’t covariant. Even thoughTderives fromobject,List<T>doesn’t derive fromList<object>.Consider this method:
If you could cast
List<int>toList<object>, you could pass aList<int>to that method and it would turn into something else.This is going to change when covariant generics are introduced in C# 4.0. This article is a pretty good explanation of the issues involved.
But to solve your actual problem, this will do the trick: