I have the following classes:
public class BagA : Dictionary<string, BagB>
{}
public class BagB : Dictionary<string, object>
{}
Now, through reflection I’m creating an object of type BagB which I’m
trying to add to an object I created of type BagA:
object MyBagA // Created through reflection
object MyBagB // Created through reflection
((Dictionary<string,object>)MyBagA).Add("123",MyBagB); //This doesnt work
Gives me the following error: Unable to cast object of type ‘BagA’ to type ‘System.Collections.Generic.Dictionary`2[System.String,System.Object]’.
Why can’t I cast a Dictionary<string, BagB> to Dictionary<string, object>?
Which is the best way to add my Item based on this scenario? perhaps Anonymous methods..?
Notice that I would prefer not having to modify my classes BagA and BagB…
Thanks!
Since you used reflection to create your objects, it’s only fair that you need to continue using it to call their methods: