I don't understand why I'd create an IEnumerable. Or why it's important.
I'm looking at the example for IEnumerable: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
But I can basically do the same thing if I just went:
List<Person> people = new List<Person>();
so what's IEnumerable good for? Can you give me a situation where I'd need to create a class that implements IEnumerable?
IEnumerable
is an interface, it exposes certain things to the outside. While you are completely right, you could just use a List<T>
, but List<T>
is very deep in the inheritance tree. What exactly does a List<T>
? It stores items, it offers certain methods to Add
and Remove
. Now, what if you only need the "item-keeping" feature of a List<T>
? That's what an IEnumerable<T>
is - an abstract way of saying "I want to get a list of items I can iterate over". A list is "I want to get a collection which I can modify, can access by index and iterate". List<T>
offers a lot more functionality than IEnumerable<T>
does, but it takes up more memory. So if a method is taking an IEnumerable<T>
, it doesn't care what exactly it gets, as long as the object offers the possibilites of IEnumerable<T>
.
Also, you don't have to create your own IEnumerable<T>
, a List<T>
IS an IEnumerable<T>
!
Lists are, of course IEnumerable
- As a general rule, you want to be specific on what you output but broad on what you accept as input eg:
You have a sub which loops through a list of objects and writes something to the console...
You could declare the parameter is as either IEnumerable<T>
or IList<T>
(or even List<T>
). Since you don't need to add to the input list, all you actually need to do is enumerate - so use IEnumerable
- then your method will also accept other types which implement IEnumerable including IQueryable
, Linked Lists, etc...
You're making your methods more generic for no cost.
Today, you generally wouldn't use IEnumerable anymore unless you were supporting software on an older version of the framework. Today, you'd normally use IEnumerable<T>
. Amongst other benefits, IEnumerable fully implements all of the LINQ operations/extensions so that you can easily query any List type that implements IEnumerable<T>
using LINQ.
Additionally, it doesn't tie the consumer of your code to a particular collection implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With