title: Why implementation of IEnumerable not require when iterate using foreach
body: <p>I was looking into the <code>IEnumerable</code> and trying the example given in  <a href="https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx#Anchor_4" rel="nofollow">this</a> link. I understand that when we iterate using <code>foreach</code> the <code>GetEnumerator()</code> method gets call because my <code>List</code> class has implemented IEnumerable (or may be I am wrong).</p>
  
  <pre><code>   public class List&lt;T&gt; : IEnumerable
      {
          private T[] _collection;
          public List(T[] inputs)
          {
              _collection = new T[inputs.Length];
              for (int i = 0; i &lt; inputs.Length; i++)
              {
                  _collection[i] = inputs[i];
              }
          }
          IEnumerator IEnumerable.GetEnumerator()
          {
              return (IEnumerator)GetEnumerator();
          }
          public CollectionEnum&lt;T&gt; GetEnumerator()
          {
              return new CollectionEnum&lt;T&gt;(_collection);
          }
      }
  
  public class CollectionEnum&lt;T&gt; : IEnumerator
      {
          public T[] _collection ;
          int position = -1;
          public CollectionEnum(T[] list)
          {
              _collection = list;
          }
          public bool MoveNext()
          {
              position++;
              return (position &lt; _collection.Length);
          }
          //implementation on Current and Reset
      }
  </code></pre>
  
  <p>Then, it is also mentioned that implementation of <code>IEnumerable</code> is not required to iterate using <code>foreach</code>. So, in the above code if I remove the implementation of <code>IEnumerable</code> the <code>foreach</code> must work. So my <code>List&lt;&gt;</code> class looks like</p>
  
  <pre><code>public class List&lt;T&gt;
  {
      private T[] _collection;
      public List(T[] persons)
      {
          _collection = new T[persons.Length];
          for (int i = 0; i &lt; persons.Length; i++)
          {
              _collection[i] = persons[i];
          }
      }
      public CollectionEnum&lt;T&gt; GetEnumerator()
      {
          return new CollectionEnum&lt;T&gt;(_collection);
      }
  }
  </code></pre>
  
  <p>And which does work. Now I did not understand how <code>foreach</code> knows my class has a method call <code>GetEnumerator()</code> which returns a <code>IEnumerator</code> type.</p>