Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast Dictionary<string,MyClass> to Dictionary<string,object>

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!

like image 240
Adolfo Perez Avatar asked Jan 18 '23 03:01

Adolfo Perez


1 Answers

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.

like image 81
JaredPar Avatar answered Jan 30 '23 00:01

JaredPar