abarnybox abarnybox - 1 year ago 105
C# Question

How to create an anonymous type using codedom

Essentially I am aiming to get something like the following code as output from my codedom:

var foo = new { variable1 = "value", variable2 = 5 };

I won't just be using it for a variable assignment but I wanted a simple example of how to create an anonymous type. I'm not sure that this exact code is possible to achieve but if there's some kind of work around you could point me in the direction of I would be much obliged.

I've had a look at the
and I don't think that's going to do what I'm looking for and I can't find anything else that comes close.

Thanks in advance for all and any help.

Answer Source

CodeDOM attempts to be language-neutral and hasn't been updated for a very long time, so I don't think you can use any of its built-in types to do this. But you can use CodeSnippetExpression to inject this code as string:

var expression = new CodeSnippetExpression("new { variable1 = \"value\", variable2 = 5 }");
var statement = new CodeVariableDeclarationStatement("var", "foo", expression);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download