foreach IEnumerable What happens behind?


i'm trying understand how iteration works internally. i've found explanation in tutorial:

here’s foreach loop loops through list<duck> variable called duck:  foreach (duck duck in ducks) {  console.writeline(duck);  }  , here’s loop doing behind scenes:  ienumerator<duck> enumerator = ducks.getenumerator();  while (enumerator.movenext()) {  duck duck = enumerator.current;  console.writeline(duck);  }  idisposable disposable = enumerator idisposable;  if (disposable != null) disposable.dispose();

ok, how helps explain this:

static void main()  {      daysoftheweek days = new daysoftheweek();        foreach (string day in days)      {          console.write(day + " ");      }      // output: sun mon tue wed thu fri sat      console.readkey();  }    public class daysoftheweek : ienumerable  {      private string[] days = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };        public ienumerator getenumerator()      {          (int index = 0; index < days.length; index++)          {              // yield each day of week.               yield return days[index];          }      }  }
example here:

http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx

there no "movenext()" method in here, explanation above not full. there full explanation of iteration using foreach. i've been looking explanation of on msdn several hours already, i've tried:

"foreach, in (c# reference)"

"how to: access collection class foreach (c# programming guide)"

"iterators (c# , visual basic)"

"collections (c# , visual basic)"

"ienumerator interface"\"ienumerable interface"

there nothing there it.



"there no "movenext()" method in here, explanation above not full."

actually explanation full it's foreach , how foreach uses enumerators.

to understand second example need explanation in addition foreach explanation, if @ page took example there's "technical implementation" section , in there mentions compiler generates nested class.

it's nested class implements ienumerator , has movenext method. code produced compiler bit convoluted here's simplified version of it:

public class daysoftheweek : ienumerable { private string[] days = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; private class generatedenumerator : ienumerator { private object current; private int index; public object current { { return current; } } public bool movenext() { if (index < days.length) { current = days[index++]; return true; } return false; } } public ienumerator getenumerator() { return new generatedenumerator(); } }





Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

job syspolicy_purge_history job fail in sqlserver 2008

Trying to register with public marketplace error with 'Get-AzureStackStampInformation'