I’ve got an IDictionary field that I would like to expose via a property of type IDictionary<string, dynamic> the conversion is surprisingly difficult since I have no idea what I can .Cast<>() the IDictionary to.
Best I’ve got:
IDictionary properties;
protected virtual IDictionary<string, dynamic> Properties {
get {
return _properties.Keys.Cast<string>()
.ToDictionary(name=>name, name=> _properties[name] as dynamic);
}
}
If the underlying type of the
IDictionarydoes not implementIDictionary<string, dynamic>, you cannot cast the object, period. If it does, a simple cast via(IDictionary<string, dynamic>)localVarwill suffice.If it’s not, there are two things you can do:
IDictionaryto your generic type.IDictionaryas a dependency and implements the genericIDictionaryyou want, mapping calls from one to the other.Edit: The sample code you’ve just posted will copy the dictionary every time it gets called! I will edit again in a moment with some suggested code.
Option 1
your sample code approach is solid as a means of copying the data, but the copy should be cached or you’re going to copy lots of times. I’d suggest you put the actual translation code into a separate method and call that from your property the first time it’s used. For example:
Now, there are obvious cons to this approach… what if dataLayerProperties needs to be refreshed? You have to go setting translatedProperties to null again, etc.
Option 2
This is my preferred approach.
Now, there are obvious cons to this approach as well, the most glaring is the fact that the
Keys(and Value and anything else that returnsICollectiononIDictionaryhas to return a new array for every call. But this still allows the most flexible approach, since it ensures the data is always up to date.