Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why create an IEnumerable?

Tags:

c#

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?

like image 475
Shai UI Avatar asked Dec 19 '10 02:12

Shai UI


3 Answers

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>!

like image 164
Femaref Avatar answered Oct 29 '22 03:10

Femaref


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.

like image 31
Basic Avatar answered Oct 29 '22 04:10

Basic


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.

like image 36
Steven Evers Avatar answered Oct 29 '22 03:10

Steven Evers