Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Build anonymous object dynamically

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.
like image 482
amd Avatar asked Nov 12 '18 14:11

amd


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

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

like image 101
Patrick Hofman Avatar answered Sep 21 '22 18:09

Patrick Hofman