2

how can we add properties dynamically to existing class which already have some properties.

Suppose I have method with return type IList

Employee class has 3 properties, but in some cases by method returns extra properties which are not exists in the Employee class and this dynamic properties may change on each call.

So based on results we have to add properties dynamically apart from existing properties using C#

  • Take a look at https://weblog.west-wind.com/posts/2012/Feb/08/Creating-a-dynamic-extensible-C-Expando-Object – int21h Nov 22 '17 at 05:03
  • Use [`ExpandoObject`](https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/) – mmushtaq Nov 22 '17 at 05:21
  • In addition to my answer, you could perhaps also try the [decorator pattern](https://stackoverflow.com/questions/40294622/understanding-decorator-design-pattern-in-c-sharp) if it suits your needs. – ProgrammingLlama Nov 22 '17 at 05:52

2 Answers2

1

I'm using the following to create a shallow copy of an object into an ExpandoObject so that I can assign extra properties. This could work for you.

private dynamic ConvertToExpandoObject<T>(T value)
{
    var result = new ExpandoObject();
    var valueType = typeof(T);
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(valueType))
    {
        result[property.Name] = property.GetValue(value);
    }
    return result as ExpandoObject;
}

Example:

Employee e = db.GetEmployee(1);
dynamic expandableEmployee = ConvertToExpandoObject(e);
expandableEmployee.ExpectedYearsOfService = 10*1000;

Note this field won't be added to the original object.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
-3

Use dynamic

dynamic d = yourExistingObject;
d.newProperty = "string for example";
Xin
  • 33,823
  • 14
  • 84
  • 85