BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Algorithms and Data Structures
.NET 2.0+

A Generic Read-Only Dictionary

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.

Count Property

The final IDictionary property that will be retrieved directly from the wrapped dictionary is the Count property. This simply returns the number of items in the collection. To add this property, add the following code:

public int Count
{
    get { return _dictionary.Count; }
}

IsReadOnly Property

To complete the class members that are implemented by the ReadOnlyDictionary directly, we need to add the IsReadOnly property. This returns a Boolean value that indicates whether a dictionary is read-only or writeable. For the new dictionary, the return value will always be true.

public bool IsReadOnly
{
    get { return true; }
}

Implementing IDictionary<> and ICollection<>

To complete the class, we now need to implement the remaining members from the IDictionary and ICollection generic interfaces. Each of these members performs some modification of the contents of the ReadOnlyDictionary and therefore will throw an exception. To complete the class, add the remainder of the code as follows:

void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
    throw new NotSupportedException();
}

bool IDictionary<TKey, TValue>.Remove(TKey key)
{
    throw new NotSupportedException();
}

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
    throw new NotSupportedException();
}

bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
    throw new NotSupportedException();
}

void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
    throw new NotSupportedException();
}

Using the ReadOnlyDictionary

The use of the ReadOnlyDictionary is similar to that of the in-built ReadOnlyCollection. To create a read-only dictionary we must first create a writeable one. This is then wrapped using the constructor of the new class. A dictionary-based version of the example at the beginning of this article would be as follows:

Dictionary<int, string> writeable = new Dictionary<int, string>();
writeable.Add(1, "One");
writeable.Add(2, "Two");
writeable.Add(3, "Three");

ReadOnlyDictionary<int, string> readOnly = new ReadOnlyDictionary<int, string>(writeable);
28 February 2009