Coder Perfect

How to properly populate a C# dictionary with values

Problem

In a C# file, I’m making a dictionary with the following code:

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

Under new, there is a red line with the error:

So, what exactly is going on here?

Version 2 of.NET is what I’m working with.

Asked by azrosen92

Solution #1

In a simple.NET 4.0 console application, I can’t duplicate the problem:

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

        Console.ReadKey();
    }
}

Could you try reproducing it in a basic Console application and see where that takes you? It appears that you’re aiming for.NET 2.0 (which doesn’t support initialization syntax) or the client profile framework, rather than a version of.NET that does.

Answered by Haney

Solution #2

You may make a dictionary in C# 6.0 by doing the following:

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

It works with custom kinds as well.

Answered by Vikram Kumar

Solution #3

Inline initialization of a Dictionary (and other collections) is possible. Braces are used to keep each member in place:

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.

Answered by Brendan

Solution #4

Assume we have a dictionary that looks 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");

This is how we can set things up.

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

Answered by Debendra Dash

Solution #5

In C# 3.0, object initializers were introduced. Make sure you’re using the right framework version.

C# 3.0: A Quick Overview

Answered by Zbigniew

Post is based on https://stackoverflow.com/questions/17047602/proper-way-to-initialize-a-c-sharp-dictionary-with-values