| Liquid Development Is What I Do
Seb Nilsson

Convert C# Anonymous (or Any) Types Into Dynamic ExpandoObject

There are scenarios when you need to convert an anonymous type in C#, or any other type, into a dynamic, or more specifically to the underlying ExpandoObject-type.

My specific need was to be able to move the data from an anonymous type from the current assembly into a dynamically executed external assembly. So I created an extension-method for this, which moves all the properties from any object into a new ExpandoObject.

public static ExpandoObject ToExpandoObject(this object obj)
    // Null-check

    IDictionary expando = new ExpandoObject();

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

    return (ExpandoObject) expando;

You can use the extension-method on any type of object and choose to reference the resulting type by it's actual type ExpandoObject or as a dynamic.

var anonymous = new {Id = 123, Text = "Abc123", Test = true};

dynamic dynamicObject = anonymous.ToExpandoObject();
ExpandoObject expandoObject = anonymous.ToExpandoObject();

Since the code uses the type System.ComponentModel.TypeDescriptor, if you use .NET Core or .NET Standard, you might need to reference the Nuget-package named System.ComponentModel.TypeConverter.