1

I have a library that is doing a bunch of reflection work relying on the PropertyInfo of the classes it receives (to get and set values).

Now I want to be able to work with dynamic objects, but I can't find how to get the PropertyInfo of a dynamic's properties. I've checked the alternatives, but for those I'd need to change everywhere I use PropertyInfo to get/set values.

dynamic entity = new ExpandoObject();
entity.MyID = 1;

// - Always null
PropertyInfo p = entity.GetType().GetProperty("MyID");
// - Always null
PropertyInfo[] ps = entity.GetType().GetProperties();

// - These are called everywhere in the code
object value = p.GetValue(entity);
p.SetValue(entity, value);

Is it possible to get or create a PropertyInfo somehow just to be able to use it's GetValue() and SetValue() on a dynamic object?

Danicco
  • 1,573
  • 2
  • 23
  • 49
  • 1
    I can't reproduce this. Are you certain that the property `MyID` exists on the entity and is public? – David L Jun 27 '16 at 15:56
  • @DavidL Sorry, I'll post a better example. It's a dynamic so the property will only exist if it has been set and it's public. – Danicco Jun 27 '16 at 15:59
  • Note that it may not be an actual property. Some types like `ExpandoObject` _simulate_ properties by redirecting the runtime binding to a name/value dictionary. – D Stanley Jun 27 '16 at 16:05
  • I also cannot reproduce it, `GetProperties()` _is_ returning an array full of `PropertyInfo` for my `dynamic` variables. – René Vogt Jun 27 '16 at 16:05
  • See if [this](http://stackoverflow.com/a/19139499/986184) or [this](http://stackoverflow.com/a/7897621/986184) can help you – Dudi Keleti Jun 27 '16 at 16:07

1 Answers1

0

Under the covers an ExpandoObject is really just a dictionary. You can get at the dictionary just by casting it.

dynamic entity = new ExpandoObject();
entity.MyID = 1;

if(entity.GetType() == typeof(ExpandoObject))
{
    Console.WriteLine("I'm dynamic, use the dictionary");
    var dictionary = (IDictionary<string, object>)entity;
}
else
{
    Console.WriteLine("Not dynamic, use reflection");
}

You could modify your Mapping method to check if the object being passed in is dynamic and route through a different path that just iterates over the keys of the dictionary.

https://dotnetfiddle.net/VQQZdy

Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • I'm trying to avoid the dictionary cast since I'll have to change every place in the code that assumes `PropertyInfo`, which is pretty much everywhere now... – Danicco Jun 27 '16 at 16:18