I've read a lot about how ExpandoObject can be used to dynamically create objects from scratch by adding properties, but I haven't yet found how you do the same thing starting from a non-dynamic C# object that you already have.
For instance, I have this trivial class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}
I would like to convert this to ExpandoObject so that I can add or remove properties based on what it has already, rather than rebuilding the same thing from scratch. Is this possible?
Edit: the questions marked as duplicate are clearly NOT duplicates of this one.
You can not "convert" a
Person
class in to a expando object. However you could create a wrapperDynamicObject
that contains aPerson
and forwards all of the fields.example usage
It could be done like this: