Can I use a collection initializer for Dictionary<TKey, TValue> entries?

C#.NetGenericsCollectionsC# 3.0

C# Problem Overview


I want to use a collection initializer for the next bit of code:

public Dictionary<int, string> GetNames()
{
    Dictionary<int, string> names = new Dictionary<int, string>();
    names.Add(1, "Adam");
    names.Add(2, "Bart");
    names.Add(3, "Charlie");
    return names;
}

So typically it should be something like:

return new Dictionary<int, string>
{ 
   1, "Adam",
   2, "Bart"
   ...

But what is the correct syntax for this?

C# Solutions


Solution 1 - C#

var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};

Solution 2 - C#

The syntax is slightly different:

Dictionary<int, string> names = new Dictionary<int, string>()
{
    { 1, "Adam" },
    { 2, "Bart" }
}

Note that you're effectively adding tuples of values.

As a sidenote: collection initializers contain arguments which are basically arguments to whatever Add() function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:

class FooCollection : IEnumerable
{
    public void Add(int i) ...

    public void Add(string s) ...

    public void Add(double d) ...
}

the following code is perfectly legal:

var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };

Solution 3 - C#

return new Dictionary<int, string>
{ 
   { 1, "Adam" },
   { 2, "Bart" },
   ...

Solution 4 - C#

The question is tagged c#-3.0, but for completeness I'll mention the new syntax available with C# 6 in case you are using Visual Studio 2015 (or Mono 4.0):

var dictionary = new Dictionary<int, string>
{
   [1] = "Adam",
   [2] = "Bart",
   [3] = "Charlie"
};

Note: the old syntax mentioned in other answers still works though, if you like that better. Again, for completeness, here is the old syntax:

var dictionary = new Dictionary<int, string>
{
   { 1, "Adam" },
   { 2, "Bart" },
   { 3, "Charlie" }
};

One other kind of cool thing to note is that with either syntax you can leave the last comma if you like, which makes it easier to copy/paste additional lines. For example, the following compiles just fine:

var dictionary = new Dictionary<int, string>
{
   [1] = "Adam",
   [2] = "Bart",
   [3] = "Charlie",
};

Solution 5 - C#

If you're looking for slightly less verbose syntax you can create a subclass of Dictionary<string, object> (or whatever your type is) like this :

public class DebugKeyValueDict : Dictionary<string, object>
{

}

Then just initialize like this

var debugValues = new DebugKeyValueDict
                  {
                       { "Billing Address", billingAddress }, 
                       { "CC Last 4", card.GetLast4Digits() },
                       { "Response.Success", updateResponse.Success }
                  });

Which is equivalent to

var debugValues = new Dictionary<string, object>
                  {
                       { "Billing Address", billingAddress }, 
                       { "CC Last 4", card.GetLast4Digits() },
                       { "Response.Success", updateResponse.Success }
                  });

The benefit being you get all the compile type stuff you might want such as being able to say

is DebugKeyValueDict instead of is IDictionary<string, object>

or changing the types of the key or value at a later date. If you're doing something like this within a razor cshtml page it is a lot nicer to look at.

As well as being less verbose you can of course add extra methods to this class for whatever you might want.

Solution 6 - C#

In the following code example, a Dictionary<TKey, TValue> is initialized with instances of type StudentName.

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

from msdn

Solution 7 - C#

Yes we can use collection initializer in dictionary.If 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 follow.

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

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
QuestionGerrie SchenckView Question on Stackoverflow
Solution 1 - C#bruno condeView Answer on Stackoverflow
Solution 2 - C#Anton GogolevView Answer on Stackoverflow
Solution 3 - C#yboView Answer on Stackoverflow
Solution 4 - C#Nate CookView Answer on Stackoverflow
Solution 5 - C#Simon_WeaverView Answer on Stackoverflow
Solution 6 - C#BellashView Answer on Stackoverflow
Solution 7 - C#Debendra DashView Answer on Stackoverflow