2

I noticed this code in our project

Dictionary<int, IList> someDict = new Dictionary<int, IList>();

What's the idead of using interface for value? Does that means that I can put in every list that implements/support IList ? For example, can I put L List<int>and List<string> for values in the dictionary ?

Dimitar Tsonev
  • 3,711
  • 5
  • 40
  • 70

4 Answers4

4

It allows you to have a more generic type, so it will become easier to refactor if you change the type later.

List<T> or IList<T>

The best way to reduce refactoring job is to use IEnumerable when possible.

Community
  • 1
  • 1
AlexH
  • 2,650
  • 1
  • 27
  • 35
  • 1
    But 'IEnumrable' is not suitable in the cases when you need to add or delete elements, since it doesn't support them ? In that cases, 'IList" is preferable. I got the idea, thanks! – Dimitar Tsonev Nov 29 '12 at 09:25
2

You can put any implementation of IList as a value

Dictionary<int, IList> someDict = new Dictionary<int, IList>();
someDict[1] = new List<string>() { "Hello", "World" };
someDict[2] = new List<int>() { 42 };
someDict[3] = new int[] { 1, 2, 3 };
someDict[4] = new ArrayList();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

Yes, you want to be decoupled from a special class, you just want to make sure that the type used in the dictionary provides the IList funcionality. As long as your type provides this you can use it, including List<T>. It's like a contract which ensures a set of methods/properties on the type

DerApe
  • 3,097
  • 2
  • 35
  • 55
1

Yes, you can use types that inherit from from type declared. In your case List<int> is generic type built from List<T>, which in turn inherits from IList. For that reason, yes, you can use List<int> in your dictionary.

Nikola Radosavljević
  • 6,871
  • 32
  • 44