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
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.
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.
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.
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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With