Difference between IEnumerator and IEnumerable

IEnumerator is an interfaces. An IEnumerator is a that can enumerate. It has 2 methods (MoveNext and Reset) and a property Current. To use IEnumerator is if you want a nonstandard way of enumerating (not iterating one-by-one) and want to define custom iteration. You create a new class implementing IEnumerator. Code Snippet:
    public class MyCustomIterate:IEnumerator
    {
        public object Current
        {
            get { throw new NotImplementedException(); }
        }
        public bool MoveNext()
        {
            throw new NotImplementedException();
        }
        public void Reset()
        {
            throw new NotImplementedException();
        }
    }


IEnumerable  is also an interfaces. An IEnumerable is that can be enumerated. It has just one method called GetEnumerator that returns an enumerator that iterates through a collection. When you implement enumerator logic in any of your collection class, you need to implement IEnumerable (either generic or non generic). Code Snippet:
    public class IterateTest : IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }

Comments

Popular posts from this blog

Hosting WCF in IIS(9 Steps)

MVC and MVVM Architecture