Initialize a Dictionary in C#

The post Initialize two-dimensional arrays in C# explains how to initialize a two-dimensional array. Even though a Dictionary is a more complicated data type, 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 int 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.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in syntax and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *