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;
} 
Community
  • 1
  • 1
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171

1 Answers1

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
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53