Why can we use foreach without IEnumerator/IEnumerable

  • Thread starter Thread starter cody
  • Start date Start date
C

cody

Why was this design decision to use this kind of "duck typing" in that case?

All you have to do is have a method GetEnumerator() which returns an
object providing Current and MoveNext(). IEnumerator and IEnumerable are
not necessary. Why is that? And what are these interface good for then?
Just dummy/marker interfaces like Cloneable in java?
 
The interface is handy for when you need to talk about an abstract
"something that is enumerable, but I don't know what yet" - for
instance in the ctor of List<T>(IEnumerable<T>)

I can't explain the duck-typing ;-p

Marc
 
Why was this design decision to use this kind of "duck typing" in that case?

So that you could do strongly typed enumerations (including there
being no boxing penalty) before generics came along.

I suspect that if it was designed today with generics already present,
it wouldn't be done the same way. Having said that, I believe the
query expression transformations performed by the C# 3 compiler
require appropriate method names but not any particular interface.
All you have to do is have a method GetEnumerator() which returns an
object providing Current and MoveNext(). IEnumerator and IEnumerable are
not necessary. Why is that? And what are these interface good for then?
Just dummy/marker interfaces like Cloneable in java?

No, there are lots of things which *do* require IEnumerable. It's not
just for foreach!

Jon
 
Jon said:
So that you could do strongly typed enumerations (including there
being no boxing penalty) before generics came along.

I suspect that if it was designed today with generics already present,
it wouldn't be done the same way. Having said that, I believe the
query expression transformations performed by the C# 3 compiler
require appropriate method names but not any particular interface.

Yes, I also heard of that.
 

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

Back
Top