BLOG.CSHARPHELPER.COM: Initialize a Dictionary in C#
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 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.
Comments