IEnumerable<T>

P

Peter Morris

I've given this interface some thought, the benefits to using it seem to be

01: I can use "var" in a foreach

//Works
List<SomeClass> list = new List<SomeClass>();
foreach(var item in list)
item.MethodOnSomeClass();

//Doesn't work
ArrayList list2 = new ArrayList();
foreach(var item in list2)
item.MethodOnSomeClass(); //item is treated as System.Object


02: Type checking

//This compiles
ArrayList list2 = new ArrayList();
list2.Add(new Person());

foreach(NotAPersonClass item in list2)
item.MethodOnNotAPersonClass();


//This does not compile
List<Person> list = new List<Person>();
foreach(NotAPersonClass item in list)
item.MethodOnNotAPersonClass();


Are there any other benefits of IEnumerable<T> over IEnumerable that I have
not considered?



Pete
 
A

Anthony Jones

Peter Morris said:
I've given this interface some thought, the benefits to using it seem to be

01: I can use "var" in a foreach

//Works
List<SomeClass> list = new List<SomeClass>();
foreach(var item in list)
item.MethodOnSomeClass();

//Doesn't work
ArrayList list2 = new ArrayList();
foreach(var item in list2)
item.MethodOnSomeClass(); //item is treated as System.Object


02: Type checking

//This compiles
ArrayList list2 = new ArrayList();
list2.Add(new Person());

foreach(NotAPersonClass item in list2)
item.MethodOnNotAPersonClass();


//This does not compile
List<Person> list = new List<Person>();
foreach(NotAPersonClass item in list)
item.MethodOnNotAPersonClass();


Are there any other benefits of IEnumerable<T> over IEnumerable that I have
not considered?

Here is a couple:-

When working with a value type it doesn't get boxed.

foreach on a IEnumerable would do an 'explicit' cast 'implicitly' at
run-time. The extra code needed is eliminated by tighter compile time info.
 
T

Tim Jarvis

Peter said:
Are there any other benefits of IEnumerable<T> over IEnumerable that
I have not considered?

Well of course the "big ticket item" benefit is that there are a bunch
of Linq extension methods for IEnumerable<T> and not there for
IEnumerable.

Cheers Tim.

--
 
J

Jon Skeet [C# MVP]

Peter Morris said:
I've given this interface some thought, the benefits to using it seem to be

Are there any other benefits of IEnumerable<T> over IEnumerable that I have
not considered?

What kind of use are you talking about? If you're *implementing*
IEnumerable and considering whether or not to use the generic form,
then *absolutely* you should - it provides a much more expressive API.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top