I was looking into the IEnumerable
and trying the example given in this link. I understand that when we iterate using foreach
the GetEnumerator()
method gets call because my List
class has implemented IEnumerable (or may be I am wrong).
public class List<T> : IEnumerable
{
private T[] _collection;
public List(T[] inputs)
{
_collection = new T[inputs.Length];
for (int i = 0; i < inputs.Length; i++)
{
_collection[i] = inputs[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
public CollectionEnum<T> GetEnumerator()
{
return new CollectionEnum<T>(_collection);
}
}
public class CollectionEnum<T> : IEnumerator
{
public T[] _collection ;
int position = -1;
public CollectionEnum(T[] list)
{
_collection = list;
}
public bool MoveNext()
{
position++;
return (position < _collection.Length);
}
//implementation on Current and Reset
}
Then, it is also mentioned that implementation of IEnumerable
is not required to iterate using foreach
. So, in the above code if I remove the implementation of IEnumerable
the foreach
must work. So my List<>
class looks like
public class List<T>
{
private T[] _collection;
public List(T[] persons)
{
_collection = new T[persons.Length];
for (int i = 0; i < persons.Length; i++)
{
_collection[i] = persons[i];
}
}
public CollectionEnum<T> GetEnumerator()
{
return new CollectionEnum<T>(_collection);
}
}
And which does work. Now I did not understand how foreach
knows my class has a method call GetEnumerator()
which returns a IEnumerator
type.