Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dictionary read only in C#

Tags:

I have a Dictionary<string, List<string>> and would like to expose the member as read only. I see that I can return it as a IReadOnlyDictionary<string, List<string>>, but I can't figure out how to return it as an IReadOnlyDictionary<string, IReadOnlyList<string>>.

Is there a way to do this? In c++ I'd just be using const, but C# doesn't have that.

Note that simply using a IReadOnlyDictionary does not help in this case, because I want the values to be read only as well. It appears the only way to do this is build another IReadOnlyDictionary, and add IReadOnlyList to them.

Another option, which I wouldn't be thrilled with, would be to create wrapper which implements the interface IReadOnlyDictionary>, and have it hold a copy of the original instance, but that seems overkill.

like image 420
bpeikes Avatar asked Aug 22 '16 18:08

bpeikes


1 Answers

It would be as easy as casting the whole dictionary reference to IReadOnlyDictionary<string, IReadOnlyList<string>> because Dictionary<TKey, TValue> implements IReadOnlyDictionary<TKey, TValue>.

BTW, you can't do that because you want the List<string> values as IReadOnlyList<string>.

So you need something like this:

var readOnlyDict = (IReadOnlyDictionary<string, IReadOnlyList<string>>)dict                         .ToDictionary(pair => pair.Key, pair => pair.Value.AsReadOnly()); 

Immutable dictionaries

This is just a suggestion, but if you're looking for immutable dictionaries, add System.Collections.Immutable NuGet package to your solution and you'll be able to use them:

// ImmutableDictionary<string, ImmutableList<string>> var immutableDict = dict            .ToImmutableDictionary(pair => pair.Key, pair => pair.Value.ToImmutableList()); 

Learn more about Immutable Collections here.

like image 66
Matías Fidemraizer Avatar answered Sep 18 '22 18:09

Matías Fidemraizer