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:

image2              image3

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:

image1

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.

3 Comments

  • What's a practical use of this/areas where it is applicable? This reminds me of HTML5 where we have many tags that do the same thing "Div" does, just has a different name.

  • Phil,

    Here's a scenario: What if you want to pass a dictionary and ensure that it does not get changed by the consumer?

    Arun

  • Shame there's no equivalent to the List's "AsReadOnly" method on the Dictionary class:
    http://msdn.microsoft.com/en-us/library/1e8ecdh9%28v=VS.110%29.aspx

    I wonder if they'll add an extension method for it, or if we'll have to write our own? (That would be *really* difficult! :P )

Comments have been disabled for this content.