Jolt.Collections : Adapters and Extensions

Within the .NET Base Class Library (BCL), there sometimes exist what appears to be an oversight in the implementation; perhaps an abstraction or specific implementation of an interface is omitted. One such example is the introduction of the HashSet<T> collection in .NET 3.5, but without a parent ISet<T> interface (it is introduced in .NET 4.0). There are usually good reasons for these apparent oversights, however, sometimes the missing implementation can be presented in a simple form and provide large usage value.

The Jolt.Collections library aims to providing such types by implementing adaptor types and interfaces.

Table of Contents

  1. ReadOnlyDictionary
    1. Usage Example

ReadOnlyDictionary<TKey, TValue>

The ReadOnlyDictionary<TKey, TValue> is a read-only adapter to IDictionary<TKey, TValue>, preventing execution of any method that modifies the underlying dictionary (i.e. Add(), Remove(), Clear(), and set_Item()). The analogous type for an IList<T> object is
The following example demonstrates how to create a ReadOnlyDictionary<TKey, TValue>. For more information on using this type as a dictionary, see the IDictionary<TKey, TValue> interface.

using System;
using System.Collections.Generic;
using Jolt.Collections;
using Jolt.Collections.Linq;

void CreateReadOnlyAdapter()
{
  IDictionary<int, string> dictionary = new Dictionary<int, string>();
  dictionary.Add(0, "zero");
  dictionary.Add(1, "one");
  dictionary.Add{2, "two");

  ReadOnlyDictionary<int, string> readOnlyDictionary = new ReadOnlyDictionary<int, string>(dictionary);
  IDictionary<int, string> anotherReadOnlyDictionary = dictionary.AsReadOnly();  // equivalent extension method

  Console.WriteLine(Object.ReferenceEquals(dictionary, readOnlyDictionary.Items));

  readOnlyDictionary.Clear();  // throws NotSupportedException
}

Last edited Aug 8, 2010 at 7:40 AM by SteveGuidi, version 7

Comments

No comments yet.