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

39,069

Solution 1

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

Solution 2

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

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

Solution 4

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

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.

Share:
39,069
Gerrie Schenck
Author by

Gerrie Schenck

I work in Antwerp, Belgium as a Senior .Net Developer. My specialities include Team System, Unit Testing, SQL Reporting Services, .Net 4.5, C#.Net, WinForms, WPF, WCF and some ASP.Net, CSS and HTML5.

Updated on May 17, 2020

Comments

  • Gerrie Schenck
    Gerrie Schenck about 4 years

    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?