Convert class to dynamic and add properties

The following has worked for me in the past:

It allows you to convert any object to an Expando object.

public static dynamic ToDynamic<T>(this T obj)
{
    IDictionary<string, object> expando = new ExpandoObject();

    foreach (var propertyInfo in typeof(T).GetProperties())
    {
        var currentValue = propertyInfo.GetValue(obj);
        expando.Add(propertyInfo.Name, currentValue);
    }
    return expando as ExpandoObject;
}

Based on: http://geekswithblogs.net/Nettuce/archive/2012/06/02/convert-dynamic-to-type-and-convert-type-to-dynamic.aspx

Leave a Comment