I have a dynamic say d. I am adding some properties to it by doing the following:
((IDictionary<String, Object>)d).Add("Propname", Propvalue);
Now, when i have properties that have the same name , this obviously throws an exception. I want to allow all the properties even if they are of the same name. So, the Dictionary is a wrong choice of Data Structure . I was thinking about the BAG equivalent of JAVA in C#. I could not find anything . What is the best way of going about this ?
You seem to be completely mixing several concepts.
dynamicis a trigger that makes compiler generate late-bound code. Although it’s not verified in compile-time, it follows the same rules as the ordinary c# code. It cannot have multi-valued properties (can you have them wherever in .NET?). The only way is having a collection-valued property and adding new values to the collection. Something like this:dynamichas nothing to do withIDictionaryorLookup. Adynamicvariable could be an arbitrary object, for instance anintvalue. If you usedynamic, it’s very strange that you cast it to theIDictionaryinterface. Just callAddand the DLR will resolve the method for you (like I did above).You should usually use
dynamiconly if you interoperate with a dynamic environment (script languages, COM, etc.). If you only work with c# code – throw away all the dynamic stuff and use regular .NET collections. It will both be statically verified by the compiler and work faster.For example, you could use a
Dictionary<string, ICollection<object>>to have a dynamic dictionary:UPDATE
Oh, yes, you could try creating your own
DynamicObjectimplementation that would put values into a bag upon property assignment instead of overwriting the existing value. Specifically, you should override the TrySetMember method. But first think if you really need all this complex stuff.