C# Build anonymous object dynamically
Asked Answered
E

1

8

In C# I can easily create an anonymous object like this at the compile time:

var items = new {
 Price = 2000,
 Description = "",
 Locations = new List<string> { "", "" }  
};

My question is, it's possible to create this object at the runtime ? I've heard of emit/meta programming, but I don't know if it helps here.

Noting that these objects will be created inside a for loop (100 items or more), so I recommend techniques that allow type caching.

Thanks.

Update - Why I need this

  • One example could be implementing the Include functionality like in db.Users.Include("Users"), so I need to add the Users property at runtime on demand.
Ensemble answered 12/11, 2018 at 14:25 Comment(2)
can you post the code for for loop just to see what you are tryingHerpetology
What is the purpose of such dynamically typed types?Convolvulaceous
C
2

Anonymous types are generated on compile time, and are just regular types.

Since you are talking beyond the compilation process, you don't have the 'generate an (anonymous) type on compile time' option any more, unless you compile the type yourself to an assembly you load right after generating it. System.Reflection.Emit is your friend here. This is quite expensive though.

Personally I would skip all that hassle, and look into a type that is dynamic by nature, like ExpandoObject. You can add properties, just like you would add entries to a dictionary:

dynamic eo = new System.Dynamic.ExpandoObject();
IDictionary<string, object> d = (IDictionary<string, object>)eo;
d["a"] = "b";

string a = eo.a;

Result:

enter image description here

Convolvulaceous answered 12/11, 2018 at 14:32 Comment(2)
Thanks, isn't expando objects two slow in this case ?Ensemble
It is basically a dictionary. That can't be really that slow.Convolvulaceous

© 2022 - 2024 — McMap. All rights reserved.