721

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
azrosen92
  • 8,357
  • 4
  • 26
  • 45
  • 5
    Change targeted framework version or use the "old" way of initialization. – Sebastian Ðymel Jun 11 '13 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](https://code.google.com/p/fast-member/issues/detail?id=1)? – CodeCaster Jun 11 '13 at 15:19

8 Answers8

1132

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.

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 17
    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](http://stackoverflow.com/questions/459652/why-do-c-sharp-collection-initializers-work-this-way). – James Jun 11 '13 at 15:20
  • 1
    How do I check what version of C# I'm using or change it? – azrosen92 Jun 11 '13 at 15:33
  • 3
    The project's properties will indicate the target version of the framework. – Haney Jun 11 '13 at 15:35
  • The version of Visual Studio you are using is usually a good indicator - see here for [reference](http://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c). – James Jun 11 '13 at 15:37
  • 2
    @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 Jun 11 '13 at 15:46
  • if you're using .net 4.0 why not just write it with inline assembly? – Harry Aug 30 '23 at 11:09
333

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikram Kumar
  • 3,876
  • 1
  • 17
  • 28
45

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brendan
  • 1,034
  • 9
  • 12
45

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" }
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Debendra Dash
  • 5,334
  • 46
  • 38
14

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

Overview of C# 3.0

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
12

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 }
    };
Ed'ka
  • 6,595
  • 29
  • 30
5

With С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};
Turbcool
  • 84
  • 8
amesh
  • 1,311
  • 3
  • 21
  • 51
  • 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 Dec 08 '20 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 Oct 20 '21 at 06:31
0

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"
  }
}
Namig Hajiyev
  • 1,117
  • 15
  • 16