How to: Initialize a Dictionary with a Collection Initializer
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)

Updated: July 2009

A Dictionary<TKey, TValue> contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value. To initialize a Dictionary<TKey, TValue>, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.

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

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

Note the two pairs of braces in each element of the collection. The innermost braces enclose the object initializer for the Student, and the outermost braces enclose the initializer for the key/value pair that will be added to the students Dictionary<TKey, TValue>. Finally, the whole collection initializer for the dictionary is enclosed in braces.

To run this code, copy and paste the class into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 of the .NET Framework, and it has a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually. For more information, see How to: Create a LINQ Project.




July 2009

Updated the example's comment section.

Customer feedback.

© 2016 Microsoft