Monday, September 30, 2013

Simple example of IEnumerable and IEnumerator in C#

Here is a simplest example of using IEnumerable and IEnumerator in C#. Since 'String' is an IEnumerable object, so we can enumerate it using IEnumerable and IEnumerator. 'String' object is just chosen for sake of simplicity. The way we are using "IEnumerable and IEnumerator" here can be extended to any IEnumerable object (such as List<T>, Dictionary<TK, TV>, Hashset, SortedSet etc)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace IEnumerableDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //The following example illustrates low-level use of IEnumerable and IEnumerator:
            string s = "How to use IEnumerable and IEnumerator";
            
            // Because string implements IEnumerable, we can call GetEnumerator():
            IEnumerator rator = s.GetEnumerator();
            
            // Iterating entire collection one by one until it reaches at the end
            while (rator.MoveNext())
            {
                // Getting the current object and cast it into its corresponding object with which
                // the IEnumerable collection is made (For example: String collection is made with char object)
 
                char curObject = (char)rator.Current;
                Console.Write(curObject + ".");
            }
           
            Console.Read();
        }
    }
}


Feel free to put your comments and concern if any.

Thanks,
Hemant

No comments:

Post a Comment