I've got an ExpandoObject that I'm sending to an external library method which takes an object. From what I've seen this external lib uses TypeDescriptor.GetProperties internally and that seems to cause some problems with my ExpandoObject.
I could go with an anonymous object instead and that seems to work but it much more convenient for me to use the ExpandoObject.
Do I need to construct my own DynamicObject and take care of it myself by implementing ICustomTypeDescriptor or am I missing something here.
Ideas?
Update
Besides the answer by somedave below (as per the comments), I added this class
public class ExpandoObjectTypeDescriptionProvider : TypeDescriptionProvider
{
private static readonly TypeDescriptionProvider m_Default = TypeDescriptor.GetProvider(typeof(ExpandoObject));
public ExpandoObjectTypeDescriptionProvider()
:base(m_Default)
{
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
var defaultDescriptor = base.GetTypeDescriptor(objectType, instance);
return instance == null ? defaultDescriptor :
new ExpandoObjectTypeDescriptor(instance);
}
}
and registered it like this:
dynamic parameters = new ExpandoObject();
TypeDescriptor.AddProvider(new ExpandoObjectTypeDescriptionProvider(), parameters);
Implementing ICustomTypeDescriptor actually isn't all that hard. Here is some sample code I adapted from some work I did with WinForms property grids (which uses TypeDescriptor and PropertyDescriptor). The trick is to also implement an appropriate PropertyDescriptor class that you can pass back from
ICustomTypeDescriptor.GetProperties()
. Thankfully the ExpandoObject makes this pretty simple by implementingIDictionary<string, object>
for dynamic retrieval of it's keys and values. Keep in mind that this may or may not work correctly (I haven't tested it) and it probably won't work for ExpandoObjects with lots of nested properties.