-2

I will explain my issue with this example:

ICollection<Employee> listOfEmployee = new List<Employee>();
//listOfEmployee = Some code;

In C#, List<T> inherits from IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T> interfaces. So this means List<T> have all methods that these intercafes have.

In this example above why do we sometimes use

ICollection<Employee> listOfEmployee = new List<Employee>();

or

IEnumerable<Employee> listOfEmployee = new List<Employee>();

etc... instead of

List<Employee> listOfEmployee = new List<Employee>();

this? Is there any performance benefits or something?

Hgrbz
  • 185
  • 3
  • 12
  • In your own code, I would use `List`, but in libraries it might be a good idea that public methods only require an interface as parameters, since it can be used more general that way. – Poul Bak May 25 '22 at 23:09
  • 1
    Indeed this is one of those topics, like delegates, that makes little sense if you view your code from the perspective of "I wrote it, I use it". If you start thinking about "I write a library that *someone else* uses" it starts to make sense to say "I only ever need to foreach this ie enumerate it, so I'll make the property IEnumerable, which lets them provide anything at all that is IEnumerable, rather than forcing them to provide a List/Array/Whatever" – Caius Jard May 26 '22 at 05:34

2 Answers2

0

In general, it's good practice to use the simplest type you need. It's more flexible in the long run if you decide to change the higher level type later on. For example, this works with no changes to your code:

ICollection<Employee> listOfEmployee = new List<Employee>();
...
listOfEmployee = new HashSet<Employee>();

If you were to use the highest level class like your second example instead:

List<Employee> listOfEmployee = new List<Employee>();
...
listOfEmployee = new HashSet<Employee>();

This would throw a compile-time error, even though you're only using methods from the ICollection<> interface. Since you don't need to access all of the higher-level functionality you get in a List<>, it's more maintainable this way to use ICollection<>.

Edit: It's also a good way to indicate what type of operations you plan on using with your object. If you only intend to iterate through the list, then maybe IEnumerable is the way to go. But if you want to add and insert objects later on, then you might use a List there instead

0

I would recommend you read up on why we use interfaces v. concrete types. In your examples, the interfaces convey, among other things, the type of operations a consumer can do on a collection. IEnumerable indicates items can only be iterated, where as ICollection allows for inserting and removing items in the collection.

Stack Undefined
  • 1,050
  • 1
  • 14
  • 23