2

I want to populate a PropertyDescriptorCollection from an ExpandoObject like this :

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj.GetType());
int propsCount = properties.Count;

but I always get 0 in propsCount even if the dynamic object has values.

How can I get arround this, knowing that I need to know the PropertyInfo of each property in the ExpandoObject.

Thank you.

yosboss
  • 21
  • 2
  • `ExpandoObject` does not have properties, hence you cannot get `PropertyInfo` for something that doesn't exist. Bu why do you need `PropertyInfo` and how it relates to "*I want to populate `PropertyDescriptorCollection`*"? – Ivan Stoev May 13 '16 at 17:27
  • The properties in an `ExpandoObject` are not real properties. The best you can do is get their names and the types of their values. – Yacoub Massad May 13 '16 at 17:27
  • 1
    You should use a custom type descriptor to provide property descriptors for your ExpandoObject. You may find [this post](http://stackoverflow.com/questions/16567283/exposing-properties-of-an-expandoobject) helpful. – Reza Aghaei May 13 '16 at 17:27
  • An Expando object implements IDictionary, so there's no need to use reflection to check which properties have the dinamyc object, the Keys collection will contain the name of the properties and the Values the properties values as object, or you can access it as theCastedDict[propertyName], so you can get all the info, name, property type, value, etc. – Gusman May 13 '16 at 17:56
  • Can you add more details why do you want to fill `PropertyDescriptorCollection`? Expando object gives you the meta information of object using indexer or by casting it to `IDictionary` as @Gusman suggesting. May be adding more requirement specs will help us see the big picture of the problem. – vendettamit May 13 '16 at 18:07
  • for those asking me why do I want to populate `PropertyDescriptorCollection` @IvanStoev, @vendettamit.. To be more specific, I have an object that needs to be serialized as Json string for logging and some properties have attributes like Hide/Mask. I want to copy the object to a new object and modify it so I can Hide/Mask those properties in the logs. – yosboss May 14 '16 at 02:28
  • knowing that my object has some dynamic properties. – yosboss May 14 '16 at 02:37
  • @yosboss You can follow the link which I addressed. But for serialization purpose, I believe you don't need to create a PropertyDescriptorCollection, it's enough to serialize a dictionary which you can simply create from your ExpandoObject. You may find [this post](http://stackoverflow.com/questions/34216252/programatically-turn-on-properties-serialization-on-net-ef-code-first/34216730#34216730) helplful. – Reza Aghaei May 14 '16 at 13:10
  • thank you @RezaAghaei, i'll look into it. – yosboss May 15 '16 at 13:40

0 Answers0