Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 607
Rob Sobers Avatar asked Oct 08 '22 12:10

Rob Sobers


People also ask

Are there dictionaries in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

What is immutable Dictionary C#?

The ImmutableDictionary<TKey,TValue> class represents an immutable, unordered collection of keys and values in C#. However, you can't create an immutable dictionary with the standard initializer syntax, since the compiler internally translates each key/value pair into chains of the Add() method.

Is readonly dictionary thread safe?

Yes you can assume it will only be initialized once. Concern 2: There is no need to worry about thread safety when you are only reading data which is never being updated by anthing. In your example the States of the US won't change too often (at least I hope not) and you can safetly read them from any thread you want.

How does dictionary work in C#?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.


1 Answers

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

like image 230
Jeff Yates Avatar answered Oct 16 '22 12:10

Jeff Yates