0

I was learning about Collections, in this case the interfaces IEnumerable and IEnumerator, I studied that with this simple example:

 string s = "Hello world";
            IEnumerator rator = s.GetEnumerator();

            while (rator.MoveNext ())
            {
                char c = (char)rator.Current;
                Console.WriteLine(c+".");
            }

But then I thought... I can do this with foreach loop, so I tried:

  foreach (char c in s)
            {
                Console.WriteLine(c+".");
            }

If I can do the same with the foreach loop, Why Do I have to use the interfaces IEnumerable and IEnumerator? What is better in performance? Imagine, I am doing a program which spell each letter of a big text, What Would I have to use? Interfaces or foreach loop?

I have been researching about foreach loops and I found that foreach works with interfaces.

1 Answers1

0

If I can do the same with the foreach loop, Why Do I have to use the interfaces IEnumerable and IEnumerator?

Except for the array, foreach loop utilises the IEnumerable and IEnumerator to display/perform the operations.

But, you cannot exactly modify the element itself using foreach loop, that is only possible on an Enumerator(Iterator in Java). You cannot remove the element using foreach loop.

What is better in performance?

Stick to the foreach loop as you shouldn't reinvent the wheel, unless you have to modify the element from the collection.

Imagine, I am doing a program which spell each letter of a big text, What Would I have to use? Interfaces or foreach loop?

This is the case where you should simply use foreach loop as you only need to spell each letter of a text, which is a string. You're not modifying the string (not creating a new string) itself.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • Oh thanks, so I only have to use these interfaces if I have to modify some element from the collection. –  Jun 03 '17 at 07:28
  • @JoseAviles - Yes, you should use the `IEnumerator` Interfaces in those cases. Else, stick to foreach loop as much as your usecase allows. – Am_I_Helpful Jun 03 '17 at 09:13