Skip to content

Instantly share code, notes, and snippets.

@dylanbeattie
Last active November 6, 2021 11:20
Show Gist options
  • Save dylanbeattie/4b1e872a5cf48cb414d4c6078723e7d9 to your computer and use it in GitHub Desktop.
Save dylanbeattie/4b1e872a5cf48cb414d4c6078723e7d9 to your computer and use it in GitHub Desktop.
An extension method on Object in C#, that converts statically-typed objects to dynamic objects with the same structure.
public static class ObjectExtensions {
public static dynamic ToDynamic(this object value) {
IDictionary<string, object> expando = new ExpandoObject();
var properties = TypeDescriptor.GetProperties(value.GetType());
foreach (PropertyDescriptor property in properties) {
expando.Add(property.Name, property.GetValue(value));
}
return (ExpandoObject)expando;
}
}
// Using this extension method, you can convert any .NET object into a dynamic object with a similar structure.
public class Customer {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
var myCustomer = new Customer {
Id = 12345,
FirstName = "Dylan",
LastName = "Beattie",
Company = "Ursatile Ltd"
};
// this won't work, because Customer doesn't have a _links field and you can't add arbitrary properties to a static type:
myCustomer._links = new {
self = new {
href = "/customers/12345";
}
}
// BUT we can do this:
var result = myCustomer.ToDynamic();
result._links = new {
self = new {
href = "/customers/12345";
}
}
// and then when we serialize result to a JSON object, we get hypermedia properties included.
var json = JsonConvert.SerializeObject(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment