Tuesday, June 17, 2014

IEnumerable and IEnumerator

 
 class Test : IEnumerable, IEnumerator
 {
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        public object Current
        {
            get { throw new NotImplementedException(); }
        }

        public bool MoveNext()
        {
            throw new NotImplementedException();
        }
        public void Reset()
        {
            throw new NotImplementedException();
        }
 }

IEnumerable has GetEnumerator() Method with IEnumerator return type. Whereas IEnumerator has one property Current (position) and two method MoveNext() and Reset().

Important Facts:- When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

 
foreach (small x in Big)
{
   ...
}
it's functionally equivalent to writing:
IEnumerator x= Big.GetEnumerator();
while (x.MoveNext())
{
   y= (Big)x.Current
   ...
}

No comments :