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;
}