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 ?