ReadOnlyDictionary in .net 4.5
Oh yea, .net 4.5 is out (although it’s still Developer Preview).
Some time back, I blogged about a ReadOnlyCollection and .net 4.5 has introduced a similar concept with a Dictionary object – a ReadOnlyDictionary type in the System.Collections.ObjectModel namespace. (same place where ReadOnlyCollection typs is declared)
1: // using System.Collections.ObjectModel;
2: static void Main()
3: {
4: IDictionary<string, int> myDictionary = new Dictionary<string, int>();
5: myDictionary.Add("a", 1);
6: myDictionary.Add("b", 2);
7: myDictionary.Add("c", 3);
8: myDictionary.Add("d", 4);
9:
10: ReadOnlyDictionary<string, int> readOnlyDictionary = new ReadOnlyDictionary<string, int>(myDictionary);
11:
12: foreach (KeyValuePair<string, int> item in readOnlyDictionary)
13: {
14: Console.WriteLine("{0} - {1}", item.Key, item.Value);
15: }
16: }
That’s how a ReadOnlyDictionary is instantiated. As expected the output of the above is:
As you see in the image on the right, there are (at least) three methods “missing” from the ReadOnlyDictionary instance – the Add(), Clear() and Remove() methods. Of course, this is a read-only dictionary so doesn’t make sense implementing them on this type.
But what if I cast this back to an IDictionary instance and try adding items to it?
1: IDictionary<string, int> castReadOnlyDictionary = (IDictionary<string, int>)readOnlyDictionary;
2:
3: castReadOnlyDictionary.Add("e", 5);
The compiler does allow execution of line 1, but when it tries to run the command in line 3, you get a NotSupportedException exception thrown:
Also in the Watch window towards the bottom of the image, you’ll see a IsReadOnly property showing true. So to make sure I can add items to a dictionary, I need to check the IsReadOnly property first.