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>
.