I have a dictionary of objects. Then I created an empty List as an element of that dictionary.
Dictionary<string, object> mydictionary = new Dictionary<string, object>();
mydictionary["names"] = new List<string>();
Then I try to add a name into the List, but couldn't.
mydictionary["names"].Add("Jack"); -> ERROR "object does not contain definition of Add"
How can I add values to this List?
Note: I can't change the dictionary type. It must be <string,object>.
CodePudding user response:
The compiler only knows that the entries are of type object, at compile time it doesnt know that this object is one that supports Add. I mean what Add would that be? You could also have a BigInteger object and a database. SO the compiler doesnt know how to do
mydictionary["name"].Add()
because it doesn't know what Add to call, or even if the object has an Add. This is because c# is a statically typed language. You need to tell the compiler what the object is
((List<string>)mydictionary["name"]).Add()
ie cast the object to the right type.
CodePudding user response:
You have to specifically mention the type of value, like
((IList<string>) mydictionary["names"]).Add("Jack");
or you can use as
(mydictionary["names"] as (IList<string>)).Add("Jack");
Why?
- Because you declared dictionary as a
<string, object>. - When you added key-value pair i.e.
mydictionary["names"] = new List<string>();, the value get stored as anobjectnot aList. - This is the reason when you are trying to add any string to a list, dictionary value is not recognized as a list,
- We fixed this problem, by type-casting an object to a list.
