Create a Strongly Typed Dictionary Collection

Problem

You need to create a key-based collection that can only contain one type of object and rejects attempts to add other data types.

Solution

Create a custom dictionary collection class by deriving from System. Collections.DictionaryBase, and implement type-safe Add, Remove, and Item methods.

Discussion

With a custom dictionary collection, you can place restrictions on the type of objects stored in the collection and on the type of object used to index items in the collection. Internally, the DictionaryBase object uses an ordinary weakly typed Hashtable, which is exposed through the protected property Dictionary. However, external code can’t directly access this collection. Instead, it must use one ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.