Collection Types - Dictionaries

The .NET 2.0 Framework introduced the IDictionary<TKey, TValue> type as a generic and thus strongly typed counterpart to IDictionary. As usual, concrete types that implement IDictionary<TKey, TValue> should implement IDictionary as well. There is a lot of overlap, and the generic interface declares more type-safe versions of some properties and methods declared in IDictionary. However, there is also a new method available on IDictionary<TKey, TValue> called TryGetValue, which you can use to attempt to get a value based on the given key. The method returns the value through an out parameter, and the actual return value from the method indicates whether the item was in the dictionary. Although you can do this same thing using the index operator and catching the KeyNotFoundException when the item is not in there, it is always more efficient to avoid exceptions if you know the item is probably not there. Using exceptions for the purpose of control flow is a practice to avoid for two reasons. First, using exceptions for control flow is inefficient, because exceptions are expensive. Second, it trivializes the fact that an exception is a truly exceptional event. When using exceptions for control flow, you’re using exceptions to handle an expected event. You’ll find more cases of this Try... method call pattern throughout the .NET Framework, because the .NET team made a concerted effort to avoid efficiency bottlenecks such as these.

When implementing generic dictionaries, you have a couple of choices from which to derive implementations. First, you can use SortedDictionary<TKey, TValue>, which provides O(log n) retrieval and implements IDictionary<TKey, TValue> as well as the collection interfaces. However, you can also choose to use KeyedCollection<TKey, TValue> in the System.Collections.ObjectModel namespace. Although it doesn’t actually implement the dictionary interfaces, it does provide O(1) retrieval most of the time. For more details, see the MSDN documentation.

Source Of Information : Apress Accelerated C Sharp 2010


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner