Why you should use IDictionary, IList, etc
When returning objects from a method try to use
IDictionary, etc instead of
Dictionary. This is especially important when the method is inside a class library which you distribute.
I had to edit a method that was returning a
Dictionary. Inside of which some complex work was being done to populate the dictionary.
The changes needed were going to be much easier if I could use and return a
ConcurrentDictionary. See here for what I was doing.
But because the method was returning a simple
Dictionary it was not as straight forward as I hoped. More work needed to be done and I had the choice of:
1. Doing the processing in a more difficult way, not involving a `ConcurrentDictionary`. 2. Moving the entries from the new `ConcurrentDictionary` to a simple `Dictionary` just before calling `return`. 3. Changing the return type of the method (and the associated interface).
I went with option three, this happened to be the easiest, but it was also the best. If the code had initially been written to return
IDictionary I would only have had to concern myself with required logic changes inside the method.
Here is a quick, but contrived, example of the flexibility gained by using
The class has a single public method which returns an
IDictionary. Depending on the boolean value of
getConcurrentDictionary it does its work using either as a simple
Dictionary or a
ConcurrentDictionary, but the caller does not need be aware of this. This gives great flexibility, the method
GetDataDictionary can change its internal implementation and even the type of dictionary it returns without any negative impact on the caller.
The caller also has the flexibility to cast the
IDictionary to a
ConcurrentDictionary as needed.
Here is how to call the method shown above.
Using the Watch window in Visual Studio we can see more info.