"for" requires you to declare the looping logic inside the parenthesis
that follow the for (initialization, condition for exiting the loop, and
operation to perform on each iteration). For instance:
for (int i=0; i<n; i++) DoSomething(i);
"foreach" uses a standarized interface (such as IEnumerable) exposed by
an object to implement all the looping logic, so you don't have to provide
it yourself:
foreach(MyElement x in MyCollection) DoSomething(x);
The preceding requires MyCollection to implement an interface that
provides the methods for enumerating the elements that it contains.
On May 19, 9:48 am, "Alberto Poblacion" <earthling-
(e-mail address removed)> wrote:
foreach(MyElement x in MyCollection) DoSomething(x);
The preceding requires MyCollection to implement an interface that
provides the methods for enumerating the elements that it contains.
Actually, foreach doesn't require IEnumerable or any other interface -
so long as an appropriate GetEnumerator() method is defined, which
returns a type with a bool MoveNext() method and a readable Current
property, foreach will work. Of course, the vast majority of the time
this *is* because IEnumerable is implemented, but it doesn't have to
be.
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.