CodeDom and collection initializers
Asked Answered
R

2

3

Is there a way to generate a dictionary initializer using the C# CodeDom? Are those supported at all?

I would like to have:

private IDictionary<string, string> map = new Dictionary<string, string>
{
    { "Name", "Value" },
    ...
};
Rosana answered 15/6, 2010 at 20:13 Comment(0)
P
5

This is not possible using the CodeDom constructs. They were not updated for collection initializers.

LukeH has an excellent blog post on the subject of 3.5 features and the CodeDom

Proposition answered 15/6, 2010 at 20:17 Comment(2)
Was afraid that's the case... Thanks anyway!Rosana
The blog post linked above explains that CodeDom was not updated for the "new" C# 3.0 features and gives an example of using CSharpCodeProvider.CompileAssemblyFromSource to compile a string of code containing a LINQ expression.Shier
P
1

You can do it but its possibly the worst nightmare ever.. Here is how I am doing it currently. (Updated my answer to reflect the question)

var constructDictionary = new CodeMemberField("Dictionary<string, string> map", @" = new Dictionary<string, string>()
{
   { Name, Value },
}");

This can also be populated once again its hackish.

string builder += " = new Dictionary<string, string>(){";
for(int i = 0; i < 10; i++)
{
   builder+="{ Name"+i+", Value"+i+" }";
}
var constructDictionary = new CodeMemberField("Dictionary<string, string> map", builder+" }");
Plate answered 3/11, 2018 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.