772

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

8 Answers 8

1200

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.

6
  • 20
    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.
    – James
    Commented Jun 11, 2013 at 15:20
  • 1
    How do I check what version of C# I'm using or change it?
    – azrosen92
    Commented Jun 11, 2013 at 15:33
  • 4
    The project's properties will indicate the target version of the framework.
    – Haney
    Commented Jun 11, 2013 at 15:35
  • The version of Visual Studio you are using is usually a good indicator - see here for reference.
    – James
    Commented Jun 11, 2013 at 15:37
  • 3
    @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.
    – Haney
    Commented Jun 11, 2013 at 15:46
352
+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
  • 2
    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" },
    – Maxter
    Commented Sep 12, 2018 at 15:50
  • 1
    Works in c# 3.1 too. var dict = new Dictionary<string, double> { ["Abc"] = 2d } Commented Jan 22, 2023 at 1:12
  • 2
    That's a new syntax I wasn't familiar with. Thanks.
    – duyn9uyen
    Commented Apr 19, 2023 at 13:25
  • 4
    Note, on duplicate keys this syntax does not throw whereas the other does (doc)
    – Vimes
    Commented Oct 10, 2023 at 2:56
  • I didn't know this syntax, thanks. It makes it easy to copy and paste dictionaries of data from other languages such as Lua.
    – Sasino
    Commented Jan 26 at 23:27
49

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
  • For what versions of C#? Was it there with the first version or was it introduced later? Commented Aug 18, 2021 at 10:57
  • I like that you did not use var or Add().
    – MikeTeeVee
    Commented Nov 9, 2021 at 19:29
48

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
  • The ReSharper answer. Commented May 22, 2019 at 19:16
21

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 }
    };
14

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

Overview of C# 3.0

5

With С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};
2
  • 2
    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
    Commented Dec 8, 2020 at 22:23
  • @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.
    – amesh
    Commented Oct 20, 2021 at 6:31
1

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"
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.