0

I have two dynamic objects and I'd want to overwrite values of object A with values of object B

The problem is that both are of type dynamic

I managed to extract names of the properties with

TypeDescriptor.GetProperties(oldObject);

but I'm not sure how can I read & set dynamic property of dynamic object

something like oldObject.GetType().GetProperty("Test") won't work since even GetType().GetProperties() return empty collection

Thanks in advance

Joelty
  • 1,751
  • 5
  • 22
  • 64
  • Does this answer your question? [How to override get accessor of a dynamic object's property](https://stackoverflow.com/questions/29923280/how-to-override-get-accessor-of-a-dynamic-objects-property) I guess, that you should inherit `DynamicObject` and override its members – Pavel Anikhouski Jun 15 '20 at 07:26
  • @PavelAnikhouski Those objects & their classes are external, I'm unable to modify them – Joelty Jun 15 '20 at 07:36
  • Although not a satisfying answer, `dynamic` mostly points to a design issue somewhere else. I'd first look at the design reasons for the use of dynamic, before pushing the problem down the road – TheGeneral Jun 15 '20 at 08:04

1 Answers1

0

Below way you can get all the properties and their values.

dynamic dynamicObj = //define it
object obj = dynamicObj;
string[] propertyNames = obj.GetType().GetProperties().Select(p => p.Name).ToArray();
foreach (var name in propertyNames)
{
    object value = obj.GetType().GetProperty(name).GetValue(obj, null);
}

Use this for private fields.

obj.GetType().GetProperties(BindingFlags.NonPublic);
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197