Reputation: 952
I'm writing an MVC application and am encapsulating the grabbing and passing of a series of settings to my views via an Action Filter. I can demonstrate this works fine in the debugger. I can directly hit the properties. However, as the settings are database-backed, I want to be able to test if a setting exists before I go off and expect the related properties to be attached to the object. I get the following:
'System.Dynamic.ExpandoObject' does not contain a definition for 'ContainsKey'
Looking at the MSDN documentation, it most certainly does or at least should. My use-case also seems to fit its intended usage as well. So, as far as I can tell, I'm not doing anything "weird" with this approach. Some screenshots of what I see in the debugger:
Even though the QuickWatch window sees the settings of an object, I went back to check and most certainly do declare it as an ExpandoObject
myself. Here is the code I use to generate and fill this object.
dynamic bag = filterContext.Controller.ViewBag;
bag.Settings = new ExpandoObject();
IDictionary<string, object> settingsDictionary = (IDictionary<string, object>) bag.Settings;
foreach (KeyValuePair<string, Dictionary<string, string>> pair in settings)
{
settingsDictionary[pair.Key] = new ExpandoObject();
IDictionary<string, object> innerDictionary = (IDictionary<string, object>) settingsDictionary[pair.Key];
foreach (KeyValuePair<string, string> innerValue in pair.Value)
{
innerDictionary[innerValue.Key] = JsonConvert.DeserializeObject(innerValue.Value);
}
}
All that code runs fine without an exception being thrown. Any ideas as to what's going on here?
Upvotes: 0
Views: 2586
Reputation: 203813
ExpandoObject
provides an implementation for ContainsKey
*as an explicit interface implementation of IDictionary
. That means that you can only access the method when the variable is of the type of the interface.
So to call ContainsKey
you will need to access the ExpandoObject
instance through a variable of type IDictionary
, as you showed in your second example.
Upvotes: 6