1

I would like to know if exists, in C#, a way to add a value to an object created like this:

object myObject = new { a = "First", b = "Second" };

Can I add a new field like 'c' to myObject (after the declaration row I mean)? I've searched on doc, but I wasn't able to find anything to do this.

So, my questions are:

  1. Is it possible?
  2. How can I do that?

Thank you very much for you help!

Best regards, Andrea

erre
  • 39
  • 2
  • 6

1 Answers1

0

It is important you understand what this syntax means. First of all, new { a = "First", b = "Second" } creates an instance of an anonymous type with the specific properties you assign. This already answers your question - if an object is created this way, you can't "expand" it. Also the cast to object is mostly useless, because you lose the access to the properties (use var instead of object for new { ... }, that infers the type as the actual anonymous type you have created).

As for the general question how to expand an object dynamically with new properties, the answer is straightforward - use ExpandoObject:

dynamic myObject = new ExpandoObject();
myObject.a = "First";
myObject.b = "Second";
myObject.anything = 42;
//etc.

If you treat the instance as dynamic, every property set/get is treated as a dynamic call, and the binding is done at runtime. ExpandoObject allows adding any number of additional properties at any time. If you want to access all properties, cast it to IDictionary<string, object>.

IS4
  • 11,945
  • 2
  • 47
  • 86