Make dictionary read only in C#

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)