Is there a read-only generic dictionary available in .NET?

.NET 4.5

The .NET Framework 4.5 BCL introduces ReadOnlyDictionary<TKey, TValue> (source).

As the .NET Framework 4.5 BCL doesn’t include an AsReadOnly for dictionaries, you will need to write your own (if you want it). It would be something like the following, the simplicity of which perhaps highlights why it wasn’t a priority for .NET 4.5.

public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary)
{
    return new ReadOnlyDictionary<TKey, TValue>(dictionary);
}

.NET 4.0 and below

Prior to .NET 4.5, there is no .NET framework class that wraps a Dictionary<TKey, TValue> like the ReadOnlyCollection wraps a List. However, it is not difficult to create one.

Here is an example – there are many others if you Google for ReadOnlyDictionary.

Leave a Comment