0

I see this being done so often with ICollection and IEnumberable, seeing new objects being created from the Interface instead of the class itself. To make this simple, let's use IList vs List because I understand those two a lot more.

What is the difference between:

IList<string> People = new List<string>();

vs

List<string> People = new List<string>();

?

Similarly to IEnumerable and ICollections, can't you just use

Collections<string> People = new Collections<string>(); 

as well instead of "ICollections"? It's so confusing and why is this done?

Leron
  • 9,546
  • 35
  • 156
  • 257
Megawatt
  • 165
  • 3
  • 13
  • 2
    The difference is that the former declares the list as `IList`. It will still be a `List`, but it has to be casted to it if you wanted to use methods from `List` that doesn't exist in the interface. So why you want to limit yourself? Because now the variable `People` is more flexible. It can hold lists and also arrays. So if you'd change the implementation to use an array you wouldn't break your code. – Tim Schmelter May 09 '18 at 14:59
  • What do you exactly understand by saying `seeing new objects being created from the Interface` ? The object doesnt get `created from the interface` the object gets created from the class and is assigend to an variable that is declared as interface – Rand Random May 09 '18 at 15:00

0 Answers0