Foreach calls GetEnumerator, Current and MoveNext !!!

The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators.
Therefore, using foreach is recommended instead of directly manipulating the enumerator.

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Best way to call GetEnumerator using foreach statement

Test with Quick Example

class Program
{        
   static void Main(string[] args)
   {        
      Testing tst = new Testing();
      foreach (var item in tst)
      {
          Console.WriteLine(item);       
      }
   }
}

public class Testing : IEnumerable
{
   public IEnumerator GetEnumerator()
   {
      return (new int[] { 1, 2, 3, 4, 5}).GetEnumerator();
   }
}

Output:
-----------------
1
2
3
4
5
Press any key to continue...

You probably do not want to call GetEnumerator explicitly. Instead it is implicitly called when you use a foreach loop in C#, or a For Each loop in VB.NET.

And all operations GetEnumerator, current, Movenext taken care by foreach, put a debug point and can be seen how foreach take care off all necessary calls

Simple & Quick Example

class Program
{
   static void Main(string[] args)
   {
      Testing tst = new Testing();
      foreach (var item in tst)
      {
          Console.WriteLine(item);
      }
   }
}

public class Testing : IEnumerable
{
   public IEnumerator GetEnumerator()
   {
      return new Testing2();
   }
}

public class Testing2 : IEnumerator
{
   string[] str= { "1", "2", "3", "4", "5","6" };
   int pointer=-1;
   public object Current
   {
      get { return str[pointer]; }
   }

   public bool MoveNext()
   {
      if (pointer < str.Length-1)
      {
          pointer++;
          return true;
      }
      return false;
   }
   public void Reset()
   {
      pointer = 0;
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s