806

I am creating a dictionary in a C# file with the following code:

private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
        = new Dictionary<string, XlFileFormat>
        {
            {"csv", XlFileFormat.xlCSV},
            {"html", XlFileFormat.xlHtml}
        };

There is a red line under new with the error:

Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification

What is going on here?

I am using .NET version 2.

2
  • 6
    Change targeted framework version or use the "old" way of initialization. Commented Jun 11, 2013 at 15:19
  • In what context do you place this code? A .cs file that gets compiled by Visual Studio, or in a .cshtml? Does your project file have a languageVersion element? Commented Jun 11, 2013 at 15:19

8 Answers 8

1242

I can't reproduce this issue in a simple .NET 4.0 console application:

static class Program
{
    static void Main(string[] args)
    {
        var myDict = new Dictionary<string, string>
        {
            { "key1", "value1" },
            { "key2", "value2" }
        };

        Console.ReadKey();
    }
}

Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.

Sign up to request clarification or add additional context in comments.

6 Comments

The issue is the version of C# the OP is using, object/collection initializers weren't introduced until C# 3.0. The detail as to why it didn't work before has already been answered.
How do I check what version of C# I'm using or change it?
The project's properties will indicate the target version of the framework.
The version of Visual Studio you are using is usually a good indicator - see here for reference.
@James - Not reliably, however, as this person may be picking up some legacy work in a solution that was targeting 2.0 and isn't aware of it, for example.
|
363
+250

With C# 6.0, you can create a dictionary in the following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

5 Comments

I like your way betther, but take notes that it uses the exact same number of "boilerplate" characters per line (4) as the accepted answer with { "key2", "value2" },
Works in c# 3.1 too. var dict = new Dictionary<string, double> { ["Abc"] = 2d }
That's a new syntax I wasn't familiar with. Thanks.
Note, on duplicate keys this syntax does not throw whereas the other does (doc)
I didn't know this syntax, thanks. It makes it easy to copy and paste dictionaries of data from other languages such as Lua.
52

Suppose we have a dictionary like this:

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");

We can initialize it as follows.

Dictionary<int, string> dict = new Dictionary<int, string>
{
    { 1, "Mohan" },
    { 2, "Kishor" },
    { 3, "Pankaj" },
    { 4, "Jeetu" }
};

1 Comment

The ReSharper answer.
50

You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
    { 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
    { 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
    { 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};

See How to initialize a dictionary with a collection initializer (C# Programming Guide) for details.

2 Comments

For what versions of C#? Was it there with the first version or was it introduced later?
I like that you did not use var or Add().
24

Note that C# 9 allows Target-typed new expressions so if your variable or a class member is not abstract class or interface type duplication can be avoided:

    private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new ()
    {
        { "csv", XlFileFormat.xlCSV },
        { "html", XlFileFormat.xlHtml }
    };

Comments

14

Object initializers were introduced in C# 3.0. Check which framework version you are targeting.

Overview of C# 3.0

Comments

5

With С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};

2 Comments

Your answer (before it was edited by Turbcool) was an exact copy of the accepted answer by Haney. Please ensure future answers provide new solutions to questions.
@TylerH The answer was unique, as I have suggested the indexer-based approach(Used variables from accepted answer). But the answer was not a copy. Please refer to the edit history.
2

Here is an example of Dictionary with Dictionary value

Dictionary<string, Dictionary<int, string>> result = new()
{
    ["success"] = new() { { 1, "ok" }, { 2, "ok" } },
    ["fail"] = new() { { 3, "some error" }, { 4, "some error 2" } },
};

which is equivalent to this in JSON :

{
  "success": {
    "1": "ok",
    "2": "ok"
  },
  "fail": {
    "3": "some error",
    "4": "some error 4"
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.