1

So here my requirement: I want a data structure that has a list of strings and an integer value associated with each string. After initialization of this data structure I would like to be able to edit the integer values, but disallow the addition of more strings.

So immediately I thought that of using Dictionary<string, int>, but this doesn't satisfy my desired requirements as more keys can be added after initialization. Secondly, I thought of Hashtable, but that doesn't help me at all as the IsFixedSize variable is readonly.

Is there already a data structure that accomplishes this within the .NET Framework or should I just write my own?

Thanks for any and all help.

Derek W
  • 9,708
  • 5
  • 58
  • 67
  • 2
    I don't believe there are any existing collections that satisfy your requirement, but it should be easy to create a new class which uses a `Dictionary` under the hood. – Jon Skeet Oct 11 '13 at 20:51
  • Create your own class, which is subclass of Dictonary and override add method – Iłya Bursov Oct 11 '13 at 20:55
  • Thanks for the quick response, Jon. I was thinking that this might be the case, but I didn't want to reinvent the wheel. – Derek W Oct 11 '13 at 20:56
  • @Ilya: That sounds like a good approach. I would also have to handle the Remove method as well. What would be a good way to tell if the add/removes were happening in the constructor? – Derek W Oct 11 '13 at 21:01
  • 1
    @DerekW good question, you can use then composition, ie - your class will not be subclass of dictionary, but just contain private variable for it and provide the same interface, but without public add/remove/insert methods – Iłya Bursov Oct 11 '13 at 21:10
  • All: You cannot override Dictionary Add or Remove methods. The best class to use, which does allow you to override the methods that modify the collection's membership is System.Collections.ObjectModel.KeyedCollection. – competent_tech Oct 12 '13 at 16:22

1 Answers1

0

The data structure that we use for similar functionality is System.Collections.ObjectModel.KeyedCollection.

When you inherit this class, you can override the InsertItem method and prevent addition of new items depending on whatever situation you care to implement.

competent_tech
  • 44,465
  • 11
  • 90
  • 113