BanksySan
BanksySan

Reputation: 28500

Dynamically add properties to `dynamic` type

If I have a list of property infos, and the instance of the object they came from, how can I create another object containing those properties and values?

e.g.

public dynamic Sanitize<T>(T o)
{
    if (ReferenceEquals(o, null))
    {
        return null;
    }

    var type = o.GetType();

    var propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    dynamic sanitized = new ExpandoObject();

    foreach (var propertyInfo in propertyInfos)
    {
        var name = propertyInfo.Name;
        var value = propertyInfo.GetValue(o, null);

        // Add this property to `sanitized`
    }

    return sanitized;
}

Upvotes: 0

Views: 1298

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could cast the ExpandoObject to an IDictionary<string, object> and then manipulate it as such at runtime to add properties:

var sanitized = new ExpandoObject() as IDictionary<string, object>;

foreach (var propertyInfo in propertyInfos)
{
    var name = propertyInfo.Name;
    var value = propertyInfo.GetValue(o, null);
    sanitized.Add(name, value);
}

Upvotes: 2

Related Questions