Sunday, 2 May 2010

Lowdown on C# Dictionaries: KeyCollection Is the Actual Keys

C# has no hashtables worth speaking about - it has dictionary objects. These live in the System.Collections.Generic namespace. (The C# Hashtable class does exist but it's non-generic which means objects are stored as type Object with associated cost of boxing and unboxing).

Retrieving the keys from a Dictionary yields a KeyCollection, a non-inheritable (or "sealed" class in the C# jargon), which is not a static copy of the keys but pointers to the actual keys.

In concurrency terms, KeyCollection supports multiple concurrent readers as long as the Collection is not modified. Enumerating through this collection is not inherently thread-safe unless the collection is locked.

A key question is how do you cast the KeyCollections and ValueCollections within the Dictionary object. Both are implementing the ICollection interface, which has two methods: CopyTo (copies the elements to an Array, that also implements ICollection) and GetEnumerator.

No comments: