0

I saw a function like

public FuncA(string param1, IList<SqlParameter> sqlParamsList)

I wonder why the author was using IList instead of List? Which one is better? I know the difference between them is one is interface, the other one is class. So my final question is when to use which?

GLP
  • 3,441
  • 20
  • 59
  • 91
  • List and IList both provide polymorphic behavior. IList accomplishes polymorphism with less coupling and it doesn't burnup your single inheritance. – P.Brian.Mackey Oct 30 '13 at 13:39
  • Even `IList` might be too "restrictive". Most of the time `IEnumerable` would suffice. – Corak Oct 30 '13 at 13:44
  • If you got your answer from same site then why are you generate same question... Ha ha ha.... – Vishal Patel Oct 30 '13 at 13:48
  • If you use `IList.Add()` with a plain array, you'll get an exception. I've added an answer about this to the question for which this was a duplicate (I was adding it to this question, but it got closed before I finished writing it) – Matthew Watson Oct 30 '13 at 13:48

4 Answers4

10

More than one class can implement the IList interface. If you use IList you accept any class that implements IList.

If you use List, you can only pass List and derived classes.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
2

Using an interface is generally preferable as it makes the API more flexible for the caller. If your method accepts the interface rather than the concrete implementation, the caller can use whatever type they want (List, Array, ImmutableList...), as long as it implements IList.

MgSam
  • 12,139
  • 19
  • 64
  • 95
1

Using an interface is preferred over a concrete type in order to allow a caller to pass in any object that implements the interface.
Especially in public methods this is good practice.

Markus
  • 20,838
  • 4
  • 31
  • 55
1

I would tend towards using the IList interface parameter over the concrete implementation, unless there was some reason you absolutely HAD to have the concrete List parameter.

By using IList instead of List, your method can now accept all collection types that implement IList, which may or may not be a collection that directly inherits from List. List and any of its subclasses implement IList as well, so they would also be included in the set of available types your method could use. Using IList in this case allows you to be more flexible.

Also, in unit testing scenarios, IList may be easier to mock out, depending on what exactly you're trying to test and what your features your mocking framework has.

mclark1129
  • 7,532
  • 5
  • 48
  • 84