BlackWaspTM
Algorithms and Data Structures
.NET 2.0+

A Generic Read-Only Dictionary (2)

The .NET framework includes several types of collection that are designed for use in object models. Amongst these is the ReadOnlyCollection that allows the creation of collections that may not be modified. However, there is no read-only Dictionary type.

Creating the ReadOnlyDictionary Class

To create the class definition, change the name of the default class in the project to "ReadOnlyDictionary" and modify the declaration for the class as follows:

public sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey,TValue>
{
}

In the above declaration, the class is defined as sealed to prevent it being subclassed with a type that would permit changes to the dictionary's contents. If you prefer to allow other classes to inherit from the new dictionary type, remove the sealed keyword.

The read-only dictionary uses two generic types. The first, named "TKey", defines the type of the key for each element in the collection. The second, "TValue", defines the type of each value. The actual types used for an instance of the ReadOnlyDictionary will be determined when the object is declared.

The final part of the declaration indicates that the new class will implement the generic IDictionary interface, using the same types for the keys and values. This will allow the ReadOnlyDictionary to be used wherever an IDictionary is expected, assuming that it will not require that the dictionary be modified.

The class will use functionality from several namespaces. To allow a simplified syntax, ensure that you include the following using directives at the top of the class' code file:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

Declaring the Underlying Dictionary

The ReadOnlyDictionary class will provide a wrapper to any dictionary class that implements the generic IDictionary interface. To permit this, we need to create a private field to contain a reference to that dictionary. To do so, add the following declaration within the class' code block.

private IDictionary<TKey, TValue> _dictionary;

Creating the Constructor

As with the ReadOnlyCollection, the ReadOnlyDictionary class will include a single constructor. This constructor will accept a parameter containing the dictionary to be used as the source of the collection's items. As we do not know exactly which type of dictionary will be provided, this parameter will accept any object that implements IDictionary.

public ReadOnlyDictionary(IDictionary<TKey, TValue> source)
{
    _dictionary = source;
}

NB: To keep the example code as simple as possible, no validation code is included. You should add validation as required. For example, you may wish to add a check to ensure that the source dictionary is not null.

28 February 2009