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!
There is no way to do a cast here because Dictionary<string, BagB>
and Dictionary<string, object>
are different incompatible types. Instead of casting the Dictionary
why not cast the values instead?
MyBagA.Add("123", (BagB)MyBagB);
If it were legal to cast the Dictionary<TKey, TValue>
then then very evil things could happen. Consider
Dictionary<string, BagB> map1 = ...;
Dictionary<string, object> map2 = SomeEvilCast(map1);
map2["foo"] = new object();
What would now happen if I tried to access map1["foo"]
? The type of the value is object
but it's statically typed to BagB
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With