0

In C#, Expando objects are declared, then members are added underneath.

dynamic obj = new ExpandoObject();
obj.age = 27;
obj.name = “John”;

What about a custom dynamic class that takes a tuple argument as an assignment (string,object,….,string,object)

So objects can be defined like

dynamic obj = (“age”,27,”name”,”john”);

I know this alone would result in assigning a tuple. But wouldn’t it be nice to have expando object constructors?

Alexei Levenkov
  • 96,782
  • 12
  • 124
  • 169
Tim
  • 150
  • 9
  • Does anonymous object initializer syntax work (sorry, I'm not near a compiler). This seems mote likely to be accepted: `var obj = new ExpandoObject {age = 27, name = ”john”};` or perhaps `dynamic obj = new {age = 27, name = "john”};` – Flydog57 Dec 26 '21 at 04:58
  • @Flydog57 Neither of those work, ExpandoObject only allows properties after it has been constructed. – Tim Dec 26 '21 at 05:05
  • 2
    *But wouldn’t it be nice to have expando object constructors?* - no – Caius Jard Dec 26 '21 at 06:52
  • 1
    If you really had your heart set on a 1 liner, an extension method gets you close. `static ExpandoObject WithMembers(this ExpandoObject e, params object?[] members)`, cast ExpandoObject to a dictionary and add the params in with as much sanity checking as you do/don't want – Tonu Dec 26 '21 at 07:15
  • That is, in essence, the problem with the question; SO is not designed for questions answered with opinions. Apologies for pasting the wrong link, I meant to link to https://stackoverflow.com/questions/7478048/why-cant-i-do-this-dynamic-x-new-expandoobject-foo-12-bar-twelve – Caius Jard Dec 26 '21 at 07:50

0 Answers0