662

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,030
  • 21
  • 100
  • 124
azrosen92
  • 7,727
  • 4
  • 24
  • 44
  • 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

1049

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
  • 30,180
  • 7
  • 56
  • 67
  • 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
294

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,030
  • 21
  • 100
  • 124
Vikram Kumar
  • 3,476
  • 1
  • 16
  • 28
  • 13
    For people more interested in this new syntax here is good blog post: https://marcin-chwedczuk.github.io/object-and-collection-initializers-in-csharp – csharpfolk Jun 13 '16 at 09:00
  • 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 Sep 12 '18 at 15:50
42

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,030
  • 21
  • 100
  • 124
Brendan
  • 994
  • 8
  • 12
38

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,030
  • 21
  • 100
  • 124
Debendra Dash
  • 4,742
  • 39
  • 37
13

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

Overview of C# 3.0

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Zbigniew
  • 26,284
  • 6
  • 55
  • 64
5

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,095
  • 26
  • 28
1

With С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};
Turbcool
  • 64
  • 8
amesh
  • 1,261
  • 3
  • 20
  • 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
-2

The code looks fine. Just try to change the .NET framework to v2.0 or later.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Moni
  • 12
  • 2