Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
 How to: Initialize a Dictionary wit...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Programming Guide
How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)

A Dictionary contains a collection of key/value pairs. Its Add(UTP, UTP) method takes two parameters, one for the key and one for the value. To initialize a Dictionary, 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 is initialized with instances of type Student.

C#
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 three pairs of braces in each object initializer. The innermost braces enclose the object initializer for the Scores list. The next set encloses the initializer for the Student, and the outermost braces enclose the initializer for the key/value pair that will be added to the students Dictionary. Finally, the whole collection initializer 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.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker