0

What's the advantages to use IEnumerable over List? For example I have a Employee class and a collection of employee objects, if I want to iterate each employee, I can either use:

List<Employee> employees = new List<Employee>() { new Employee(...),...}
foreach (Employee emp in employees)
{
   Console.WriteLine(emp.Name);
}

or I can use Ienumerable as :

IEnumerable<Employee> employees = new List<Employee>() { new Employee(...),...}

then use foreach loop.

Both of them achieve same goal, so why we sometimes prefer to use IEnumerable over List?

1 Answers1

1

List is a more complex structure that enables accessing values by index and supports the methods insert, add, remove and other methods. IEnumerable is a very basic interface that the List class implements as well(though it can be tricky to implement the first few times). That said, IEnumerable is used when you do not need the extras that a List provides. Otherwise, because a List has an "is a" relationship with IEnumerable you can use it the same due to the rules of contravariance that c# provides for. Here is some documentation on that:

https://msdn.microsoft.com/en-us/library/dd799517.aspx

Also on the implementation of an IEnumerable:

https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx

In conclusion, if all you need to do is use a simple iterator such as a foreach loop to cycle through the resultant IEnumerable, or use LINQ, than an IEnumerable type is great and lightweight. If you need more functionality, than the list builds upon the features that IEnumerable requires because it is an IEnumerable and then some.