Proper way to initialize a C# dictionary with values

C#Dictionary

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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

Overview of C# 3.0

Solution 6 - C#

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

Solution 7 - C#

With С# 6.0

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

Solution 8 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionazrosen92View Question on Stackoverflow
Solution 1 - C#HaneyView Answer on Stackoverflow
Solution 2 - C#Vikram KumarView Answer on Stackoverflow
Solution 3 - C#BrendanView Answer on Stackoverflow
Solution 4 - C#Debendra DashView Answer on Stackoverflow
Solution 5 - C#ZbigniewView Answer on Stackoverflow
Solution 6 - C#Ed'kaView Answer on Stackoverflow
Solution 7 - C#ameshView Answer on Stackoverflow
Solution 8 - C#MoniView Answer on Stackoverflow