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.
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));