Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use IReadOnlyDictionary?

From msdn:

Represents a generic read-only collection of key/value pairs.

However consider following:

class Test
{
    public IReadOnlyDictionary<string, string> Dictionary { get; } = new Dictionary<string, string>
    {
        { "1", "111" },
        { "2", "222" },
        { "3", "333" },
    };

    public IReadOnlyList<string> List { get; } =
        (new List<string> { "1", "2", "3" }).AsReadOnly();
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();

        var dictionary = (Dictionary<string, string>)test.Dictionary; // possible
        dictionary.Add("4", "444"); // possible
        dictionary.Remove("3"); // possible

        var list = (List<string>)test.List; // impossible
        list.Add("4"); // impossible
        list.RemoveAt(0); // impossible
    }
}

I can easily cast IReadOnlyDictionary to Dictionary (anyone can) and change it, while List has nice AsReadOnly method.

Question: how to properly use IReadOnlyDictionary to make public indeed read-only dictionary ?

like image 628
Sinatr Avatar asked Sep 14 '15 08:09

Sinatr


People also ask

What is IReadOnlyDictionary?

The IReadOnlyDictionary<TKey,TValue> interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order. The foreach statement of the C# language ( For Each in Visual Basic, for each in C++) requires the type of each element in the collection.

What is ImmutableDictionary?

An ImmutableDictionary has methods to modify it like Add or Remove , but they will create a new dictionary and return that, the original one remains unchanged and the copy of the new immutable dictionary is returned.


1 Answers

.NET 4.5 introduced the ReadOnlyDictionary type that you could use. It has a constructor that accepts an existing dictionary.

When targeting lower framework versions, use the wrapper as explained in Is there a read-only generic dictionary available in .NET? and Does C# have a way of giving me an immutable Dictionary?.

Please note that when using the latter class, the collection initializer syntax won't work; that gets compiled to Add() calls.

like image 166
CodeCaster Avatar answered Sep 29 '22 09:09

CodeCaster