0

I'm setting up a Dictionary with values of some sort of collection type as follows:

IDictionary<string, ICollection<decimal>> goodPrices = 
    new Dictionary<string, List<decimal>>();

However, this line of code results in an compilation error about not being able to implicitly convert the right-hand side to the left-hand side. Obviously, the following line produces no error:

IDictionary<string, List<decimal>> goodPrices = 
    new Dictionary<string, List<decimal>>();

So what is the correct way of declaring "goodPrices" as a set of string-collection pairs without exposing the underlying implementation of the collection?

Kris Vandermotten
  • 10,111
  • 38
  • 49
patvarilly
  • 105
  • 1
  • 5
  • 2
    You can always do `new Dictionary>()` and then just assign `List`s to dictionary keys, e.g. `goodPrices["test"] = new List { 3.30m };`... – Patryk Ćwiek Nov 20 '13 at 10:17

1 Answers1

6

What about this :

IDictionary<string, ICollection<decimal>> goodPrices = new Dictionary<string, ICollection<decimal>>();
goodPrices.Add("myString", new List<decimal>() { /* my values */ });
Réda Mattar
  • 4,361
  • 1
  • 18
  • 19
  • Ah, of course! Both your answer and @Patryk's are the way to go. I belatedly found the following SO post on the underlying reason why the implicit conversion fails: [link](http://stackoverflow.com/questions/8734272/why-cant-dictionaryt1-listt2-be-cast-to-dictionaryt1-ienumerablet2) – patvarilly Nov 20 '13 at 10:25