C# – Initialize a dictionary

You can declare a dictionary and initialize it with values by using the collection initializer syntax. Within the initializer block, you have two options for adding key/value pairs to the dictionary:

  • Indexer syntax, like [key] = value.
  • Curly brace syntax, like { key, value }.

I’ll show examples of both options below.

Note: If you have a list of items already, you can convert the list to a dictionary programmatically instead of using the initializer syntax.

Option 1 – Initialize dictionary with values using indexer syntax

Here’s an example of initializing a dictionary with multiple key/value pairs using the indexer syntax (i.e. [key]=value):

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Linda"] = 2,
    ["Teddy"] = 3
};
Code language: C# (cs)

I prefer this approach because it’s simple, intuitive, and clean (no clutter). Just be aware that adding items with the indexer means it overwrites duplicate keys (instead of throwing an exception). This is a bit of a non-issue since you’re typing in keys manually and probably won’t accidently add duplicate keys.

Option 2 – Initialize dictionary with values using curly brace syntax

Another way to initialize a dictionary is by using the curly brace syntax (i.e. { key, value }), like this:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    { "Bob", 1 },
    { "Linda", 2 },
    { "Teddy", 3 }
};
Code language: C# (cs)

Behind the scenes, this actually uses Dictionary.Add() to add the key/value pairs. This method throws an exception if you add a duplicate key. For example, this code is adding the “Bob” key twice, resulting in an exception:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    { "Bob", 1 },
    { "Bob", 2 }
};
Code language: C# (cs)

Use this curly brace syntax if 1) You prefer this style over the indexer style or 2) You want to guard against accidently adding duplicate keys. You’ll get a runtime exception and can fix the problem. With the indexer syntax, it simply overwrites the duplicate key and you probably won’t be aware that you accidently added a duplicate key at all.

Leave a Comment