I’d like to inject an instance an IDictionary<A, IList<B>> into a class, but want to keep control over the implementation of IList<B> used. The way I have of doing it — with generics — feels clunky. It makes the class definition unwieldy, and would only get worse if there were multiple similar objects I wanted to inject.
public class Lookup<T1, T2, T3> where T2 : IList<T3>, new()
{
private IDictionary<T1, T2> _underlyingDict;
public Lookup(IDictionary<T1, T2> dict)
{
_underlyingDict = dict;
}
public T2 Get(T1 key)
{
return _underlyingDict[key];
}
public void Add(T1 key, T3 value)
{
if (!_underlyingDict.ContainsKey(key))
{
_underlyingDict[key] = new T2();
}
_underlyingDict[key].Add(value);
}
}
Are there any problems with this approach, and is there a cleaner solution?
That looks okay to me, if you’re happy for the caller of the constructor to still have a reference to the dictionary that your collection is based on. I would personally change the
Addmethod to use fewer dictionary lookups though:You might also want to consider renaming the type from
Lookupgiven that that clashes withSystem.Linq.Lookup. Obviously it’s possible that you’re creating your own replacementLookupclass, which would explain this… but if there’s a chance that clients will be using both your class and “normal” LINQ, I’d consider a rename.Another option, which removes the need for the extra type parameter, is to accept a delegate to create a new instance of the relevant list type:
then where you previously had
new T2()just call_listCreator().