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

Rob Sobers picture Rob Sobers · Mar 24, 2009 · Viewed 70.2k times · Source

I'm returning a reference to a dictionary in my read only property. How do I prevent consumers from changing my data? If this were an IList I could simply return it AsReadOnly. Is there something similar I can do with a dictionary?

Private _mydictionary As Dictionary(Of String, String)
Public ReadOnly Property MyDictionary() As Dictionary(Of String, String)
    Get
        Return _mydictionary
    End Get
End Property

Answer

Jeff Yates picture Jeff Yates · Mar 24, 2009

.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.