C# Generics: Collection Interfaces
Pages: 1, 2, 3, 4, 5, 6, 7
Dictionaries
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).
To see the value of dictionaries, start by imagining that you want to keep a list of the state capitals. One approach might be to put them in an array:
string[] stateCapitals = new string[50];
The stateCapitals array will hold 50 state
capitals. Each capital is accessed as an offset into the array. For
example, to access the capital for Arkansas, you need to know that
Arkansas is the fourth state in alphabetical order:
string capitalOfArkansas = stateCapitals[3];
It is inconvenient, however, to access state capitals using array notation. After all, if I need the capital for Massachusetts, there is no easy way for me to determine that Massachusetts is the 21st state alphabetically.
It would be far more convenient to store the capital with the state name. A dictionary allows you to store a value (in this case, the capital) with a key (in this case, the name of the state).
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 and quick to retrieve values (see Table 9-6).
Table 9-6. Dictionary methods and properties
|
Method or property |
Purpose |
|---|---|
|
Public property that gets the number of elements in the
|
|
The indexer for the |
|
Public property that gets a collection containing the keys in the
|
|
Public property that gets a collection containing the values in the
|
|
Adds an entry with a specified |
|
Removes all objects from the |
|
Determines whether the |
|
Determines whether the |
|
Returns an enumerator for the |
|
Implements |
|
Removes the entry with the specified |
The key in a Dictionary can be a primitive type,
or it can be an instance of a user-defined type (an object). Objects
used as keys for a Dictionary must implement
GetHashCode() as well as
Equals. In most cases, you can simply use
the inherited implementation from Object.
IDictionary<K,V>
Dictionaries implement the IDictionary<K,V>
interface (where K is the key type and
V is the value type).
IDictionary provides a public property
Item. The Item property
retrieves a value with the specified key. In C#, the declaration for
the Item property is:
V[K key]
{get; set;}
The Item property is implemented in C# with the
index operator ([]). Thus, you access items in any
Dictionary object using the offset syntax, as you
would with an array.
Example 9-18 demonstrates adding items to a
Dictionary and then retrieving them with the
Item property.
Example 9-18. The Item property as offset operators
namespace Dictionary
{
public class Tester
{
static void Main( )
{
// Create and initialize a new Dictionary.
Dictionary<string,string> Dictionary =
new Dictionary<string,string>( );
Dictionary.Add("000440312", "Jesse Liberty");
Dictionary.Add("000123933", "Stacey Liberty");
Dictionary.Add("000145938", "John Galt");
Dictionary.Add("000773394", "Ayn Rand");
// access a particular item
Console.WriteLine("myDictionary[\"000145938\"]: {0}",
Dictionary["000145938"]);
}
}
}
Output:
Dictionary["000145938"]: John Galt
Example 9-18 begins by instantiating a new
Dictionary. The type of the key and of the value
is declared to be string.
Add four key/value pairs. In this example, the Social Security number is tied to the person's full name. (Note that the Social Security numbers here are intentionally bogus.)
Once the items are added, you access a specific entry in the dictionary using the Social Security number as key.
WARNING If you use a reference type as a key, and the type is mutable (strings are immutable), you must not change the value of the key object once you are using it in a dictionary.
If, for example, you use theEmployeeobject as a key, changing the employee ID creates problems if that property is used by theEqualsorGetHashCodemethods because the dictionary consults these methods.
Footnotes
[3] For backward compatibility, C# also provides nongeneric interfaces (e.g.,
ICollection,IEnumerator), but they aren't considered here because they are obsolescent.[4] The idiom in the FCL is to provide an
Itemelement for collection classes which is implemented as an indexer in C#.
Jesse Liberty is a senior program manager for Microsoft Silverlight where he is responsible for the creation of tutorials, videos and other content to facilitate the learning and use of Silverlight. Jesse is well known in the industry in part because of his many bestselling books, including O'Reilly Media's Programming .NET 3.5, Programming C# 3.0, Learning ASP.NET with AJAX and the soon to be published Programming Silverlight.
View catalog information for Programming C#, 4th Edition
Return to ONDotnet.com.

