Dictionary element in C#

 

A dictionary is a collection that associates a key to a value. A language dictionary, such as Webster's, associates a word (the key) with its definition (the value). That means a dictionary in C# is a key/value pair.

 

To see the value of dictionaries, start by imagining that you want to keep a list of the countries.

One approach might be to put them in an array:

 

string[] CountryCapitals = new string[100];

 

The CountryCapitals array will hold 100 countries. Each capital is accessed as an offset into the array.

 

For example, to access the capital for US, you need to know that US is the fourth state in alphabetical order.

 

string capitalOfUS = CountryCapitals[3];

 

It is not convenient to access country capitals using array notation because each time I have to know of country index in array to find out its capital. It would be far more convenient to store the capital with the country name.

 

A dictionary allows you to store a value (in this case, the capital) with a key (in this case, the name of the country). A .NET Framework dictionary can associate any kind of key (string, integer, object, etc.) with any kind of value (string, integer, object, etc.). Typically, of course, the key is fairly short, the value fairly complex.

 

The most important attributes of a good dictionary are that it is easy to add values and it is quick to retrieve values. Some dictionaries are faster at adding new values, others are optimized for retrieval. One example of a dictionary type is the hash table.