Initialize a Dictionary in C#

The example Initialize arrays, lists, and class instances in C# explains how to initialize many kinds of objects such as arrays and lists. Even though a Dictionary contains more complicated pieces of data, you can use a similar method to initialize one. Simply enclose each of the Dictionary's key/value pairs in braces.

This example uses the following code to initialize a Dictionary that uses digits as keys and that holds textual values for those digits.

// The dictionary of digit names.
private Dictionary Numbers = new Dictionary()
{
    {0, "Zero"},
    {1, "One"},
    {2, "Two"},
    {3, "Three"},
    {4, "Four"},
    {5, "Five"},
    {6, "Six"},
    {7, "Seven"},
    {8, "Either"},
    {9, "Nine"}
};

The outer pair of braces surrounds the Dictionary's entries. Each entry consists of a key/value pair surrounded by its own set of braces. The key/value pairs must contain the proper data types for the Dictionary, in this case an integer and a string.

The program uses the following code to display the values in the Dictionary (to show it was initialized properly).

// Display values from the dictionary.
private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        lstNumbers.Items.Add(i.ToString() + '\t' + Numbers[i]);
    }
}

This code loops over the digits 0 through 9 and uses the Dictionary to look up and display the corresponding textual value.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.