"satyanaray an sahoo" wrote in message
news:2008519128 1sahoo.satya198 4@gmail.com...
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(MyEleme nt 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-
quitaestoparaco ntes...@poblaci on.orgwrote:
<snip>
foreach(MyEleme nt 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.
Comment