For and for each ?

  • Thread starter Thread starter satyanarayan sahoo
  • Start date Start date
S

satyanarayan sahoo

What’s the difference between for and for each loop?

Example plz...
 
OK; just noticed all your other posts... what is this? homework? interview?

Marc
 
in message
What’s the difference between for and for each loop?

"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.

Jon
 

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