This Article perfectly describe the situation which you hit in your code.
Click
Dictionary<TKey, TValue> is able to implement IReadOnlyDictionary<TKey, TValue>, because any code that takes the latter is promising not the modify the dictionary, which is a subset of the functionality the former provides.
But consider the other direction. You start with an IReadOnlyDictionary<TKey, TValue>, and you try to turn it into a regular Dictionary<TKey, TValue>. Now, you've taken something that had previously been promised to not be modified, and turned it into something that may be modified.
Clearly, that just won't do.
Furthermore, you can't just assume that the read-only implementation would throw an exception or something when modified (e.g. run-time safety even though not compile-time safety) because, as you know, you can always get the read-only interface from a mutable implementation.
So to be safe, you have two options:
Just copy the entire dictionary contents into a new object.
Wrap the read-only object in an IDictionary<TKey, TValue> implementation that does throw an exception if you try to modify it.
Note that the latter does not actually give you what you are specifically asking for. It's close, but it's not an actual instance of Dictionary<TKey, TValue>.
In terms of copying, you have many choices. Personally, I think ToDictionary() is itself just fine. But if you really don't like the verbosity, you can wrap it in an extension method:
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(
this IReadOnlyDictionary<TKey, TValue> dictionary)
{
return dictionary.ToDictionary(x => x.Key, y => y.Value);
}
> to IList>](https://stackoverflow.com/questions/9005944/) and [Convert IList> to List
>](https://stackoverflow.com/questions/38008238/) and [still confused about covariance and contravariance & in/out](https://stackoverflow.com/questions/3445631/) and [C# generic inheritance and covariance part 2](https://stackoverflow.com/questions/14263964/)