Snj Snj - 1 month ago 6x
C# Question

Dynamically add properties to a existing object

I create the person object like this.

Person person=new Person("Sam","Lewis")

It has properties like this.


But now I want to add properties like this and set the values at the run time after creating the object.

How can I add those extra properties after creating the object. Those property name can be changed time to time. Therefor can't hardcode the "Age" and "Sex".


It's not possible with a "normal" object, but you can do it with an ExpandoObject and the dynamic keyword:

dynamic person = new ExpandoObject();
person.FirstName = "Sam";
person.LastName = "Lewis";
person.Age = 42;
person.Foo = "Bar";

If you try to assign a property that doesn't exist, it is added to the object. If you try to read a property that doesn't exist, it will raise an exception. So it's roughly the same behavior as a dictionary (and ExpandoObject actually implements IDictionary<string, object>)