1

I want to add Dynamic properties and dynamically to objects. While a similar question is answered here that uses ExpandoObject:

Dynamically Add C# Properties at Runtime

While the above answer adds properties dynamically, it does not fullfil my need. I want to be able to add variable properties.

What I reaaly want to do is to write a generic method that takes an object of type T and returns an extended object with all of the fields of that object plus some more:

public static ExpandoObject Extend<T>(this T obj)
{
    ExpandoObject eo = new ExpandoObject();
    PropertyInfo[] pinfo = typeof(T).GetProperties();
    foreach(PropertyInfo p in pinfo)
    {
        //now in here I want to get the fields and properties of the obj
        //and add it to the return value
        //p.Name would be the eo.property name
        //and its value would be p.GetValue(obj);
    }

    eo.SomeExtension = SomeValue;
    return eo;
} 

1 Answer 1

4

You could do something like this:

public static ExpandoObject Extend<T>(this T obj)
{
    dynamic eo = new ExpandoObject();
    var props = eo as IDictionary<string, object>;

    PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo p in pinfo)
        props.Add(p.Name, p.GetValue(obj));

    //If you need to add some property known at compile time
    //you can do it like this:
    eo.SomeExtension = "Some Value";

    return eo;
}

This allows you to do this:

var p = new { Prop1 = "value 1", Prop2 = 123 };
dynamic obj = p.Extend();

Console.WriteLine(obj.Prop1);           // Value 1
Console.WriteLine(obj.Prop2);           // 123
Console.WriteLine(obj.SomeExtension);   // Some Value
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.