Monday, June 20, 2011

Converting any object to dynamic

There are some scenarios in which it is useful to convert an already created object to a dynamic one, so then we can take advantage of the Dynamic Language Runtime introduced in .Net 4.0.

Two common scenarios where this conversion is useful are:
  • Passing an anonymous type to another method/object.
  • Adding a new property to an existing object.
The following code converts any object to an ExpandoObject reading all the properties of the former and adding them to the latter.

public static class DynamicExtensions
    public static dynamic ToDynamic(this object value)
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;

Using ToDynamic() to pass an anonymous type to another method

IEnumerable<dynamic> goldCustomersWithZipCode = Customers
  .Where(c => c.Type == CustomerType.Gold)
  .Select(c => new { c.Id, c.Name, c.Address.ZipCode  }.ToDynamic());


Using ToDynamic() to add a new property

Customer customer = Customers.First(c => c.Id == 1);
dynamic customerWithLastPurchase = customer.ToDynamic();
customerWithLastPurchase.LastPurchase = customer.Purchases.Last();



Marcos said...

Thank you.

Luis Carlos said...

Thankyou very very much.

Søren Lund said...

Know this is not new - But still great :)