How do you convert any C# object to an ExpandoObject?

Gigi picture Gigi · Oct 26, 2017 · Viewed 24.7k times · Source

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.

Answer

Valerii picture Valerii · Oct 26, 2017

It could be done like this:

var person = new Person { Id = 1, Name = "John Doe" };

var expando = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expando;

foreach (var property in person.GetType().GetProperties())
    dictionary.Add(property.Name, property.GetValue(person));