user19871
user19871

Reputation: 181

What is the equivalent of Java's AbstractMap in C#?

I need to create an object which exposes an IDictionary<K,V> interface, but I don't want to fill in the entire interface implemntation.

It would be nice to have the equivalent of Java's AbstractDictionary, which leaves you very little to impelment a complete dictionary (HashMap, in Java):

Upvotes: 3

Views: 965

Answers (3)

Jonathan Allen
Jonathan Allen

Reputation: 70307

If I'm building my own dictionary class, I inherit from System.Collections.ObjectModel.KeyedCollection.

EDIT for all those who don't understand API design.

You should never, ever return a generic List or Dictionary from a public property or function. Insead you should return a class specially built for that purpose. This way you can add additional functionality to it later.

Dictionay<integer, Order> Orders() {get;}
CustomerOrders Orders() {get;}

With the second version you can do things like add a Total property and have the user actually find it.

In theory you could return a subclass of Dictionary that adds the Total property, but then the user would have to A. know you are doing it, and B. include a cast to get to the property.

Upvotes: 0

Bradley Grainger
Bradley Grainger

Reputation: 28162

Wintellect's PowerCollections library includes a DictionaryBase class (source code) that implements most of the standard IDictionary<K, V> interface. From the class' documentation comments:

DictionaryBase is a base class that can be used to more easily implement the generic IDictionary<T> and non-generic IDictionary interfaces.

To use DictionaryBase as a base class, the derived class must override Count, GetEnumerator, TryGetValue, Clear, Remove, and the indexer set accessor.

Upvotes: 4

Sergiu Damian
Sergiu Damian

Reputation: 1428

System.Collections.Generic namespace contains three implementations of IDictionary<K,V>: Dictionary<TKey, TValue>, SortedDictionary<TKey, TValue> and SortedList<TKey, TValue>.

Upvotes: 3

Related Questions