Dimitar Tsonev
Dimitar Tsonev

Reputation: 3892

Why using interface in Dictionary declaration?

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 ?

Upvotes: 2

Views: 1885

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

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();

Upvotes: 2

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

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.

Upvotes: 1

DerApe
DerApe

Reputation: 3175

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

Upvotes: 1

AlexH
AlexH

Reputation: 2700

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.

Upvotes: 4

Related Questions