How to initialize a dictionary with a collection initializer (C# Programming Guide)

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 StudentName.

class StudentName
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }

class CollInit
    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 StudentName, 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.

Compiling the code

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.

See also