For and for each ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • satyanarayan sahoo

    For and for each ?

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

    Example plz...
  • Marc Gravell

    #2
    Re: For and for each ?

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

    Marc

    Comment

    • Alberto Poblacion

      #3
      Re: For and for each ?

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

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: For and for each ?

        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.

        Jon

        Comment

        Working...