94

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?

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95
  • Check this post: https://marcin-chwedczuk.github.io/object-and-collection-initializers-in-csharp – csharpfolk Jun 13 '16 at 09:01
  • Possible duplicate of [Proper way to initialize a C# dictionary with values already in it?](http://stackoverflow.com/questions/17047602/proper-way-to-initialize-a-c-sharp-dictionary-with-values-already-in-it) – Michael Freidgeim Sep 02 '16 at 08:46
  • don't think that's a dupe, because they were asking, not for the shorthand dictionary declaration syntax, but for why the shorthand wasn't working in their (ancient) setup. – NH. Jul 09 '18 at 20:49

7 Answers7

157
var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};
bruno conde
  • 47,767
  • 15
  • 98
  • 117
  • 1
    When does the initializer work? Is it only for `Dictionary` subclasses or will also work on `ICollection>`? – Shimmy Weitzhandler Dec 17 '12 at 21:48
  • after C# 3.0 you can use `var` instead of the declaring type, or if leaving the declaring type can omit the `new Dictio...` -- http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes – drzaus Jan 13 '14 at 20:24
  • 1
    @drzaus: Using var is an ugly, ugly practice though; C# is a strongly typed language. – Nyerguds Feb 24 '14 at 11:24
  • 1
    @Nyerguds: what? `var` literally just saves you keystrokes, it's [_implicitly_ strongly typed](http://msdn.microsoft.com/en-us/library/bb383973.aspx). – drzaus Feb 24 '14 at 18:24
  • @drzaus And it creates a difference between writing immediately-initialized variables and variables initialized later. It's an ugly practice. – Nyerguds Apr 01 '14 at 13:25
  • 4
    @Nyerguds -- you're entitled to your opinion, I guess, but if you're immediately initializing your variables there is literally no difference between using `var` and repeating yourself with `SomeType obj = new SomeType...`. And since you can't declare `var obj;` without immediately initializing, I just don't see the problem. Really, I'm trying to learn, but I can't grok your position. – drzaus Apr 01 '14 at 21:46
  • Not that it matters, but if you're using intellisense using var usually involves 2 MORE keystrokes; the IDE should suggest the type for you if you've already defined it. In terms of bad practice the problems only come in when you expect a collection to be of a base type, but small changes in the code can cause the IDE to switch it to the extended version. It generally doesn't cause any problems because it only happens when you're not using any of the base implementations anymore anyway, but it can cause structural problems to be hidden without you realizing. I prefer explicit declarations too. – Octopoid Mar 20 '15 at 10:14
  • @Shimmy, I think it's just a shorthand for calling `Add` multiple times. I can't remember what the exact requirements are to get it working. – Sam Dec 16 '15 at 02:26
36

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!" };
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
11
return new Dictionary<int, string>
{ 
   { 1, "Adam" },
   { 2, "Bart" },
   ...
ybo
  • 16,967
  • 2
  • 28
  • 31
10

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",
};
Nate Cook
  • 8,395
  • 5
  • 46
  • 37
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.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • This is basically how a ViewDataDictionary works in MVC - http://stackoverflow.com/questions/607985/shorthand-for-creating-a-viewdatadictionary-with-both-a-model-and-viewdata-items – Simon_Weaver Dec 23 '12 at 00:02
  • I experimented with types as 'aliases' for Dictionarys and typed arrays, presuming it would be safer, in a typed world, to use predefined types.. Turned out not to be so useful when it came to generics and linq. – Patrick Jul 07 '16 at 02:27
1

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

Bellash
  • 7,560
  • 6
  • 53
  • 86
-3

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

            }; 
Debendra Dash
  • 5,334
  • 46
  • 38
  • 4
    There are already 6 other answers showing how to do this. We don't need a 7th answer showing the same thing. – Servy May 16 '17 at 15:06