A look at IEnumerator and IEnumerable interfaces in C#

There are two interfaces which are at the base of many classes and the logic we use daily, to implement .Net based applications. These two interfaces are closely related to each other and provide a fuctionality that makes working with a Collection, fun. These are interfaces are IEnumerator and IEnumerable

Both of these interfaces work together. We need a class to implement IEnumerator interface, which provides implementations for Current property , MoveNext() and Reset() methods like below.

First, consider a class Job, around which all the logic will surround

    public class Job
    {
        public Job(string _jobName, int _duration)
        {
            this.jobName = _jobName;
            this.duration = _duration;
        }

        public string jobName;
        public int duration;
    }

Now, we have class that implements IEnumerator with an underlying array of Job objects:

    class JobsList : IEnumerator
    {
        Job[] jobs;
        int position = -1;

        public JobsList(Job[] _jobs)
        {
            jobs = _jobs;
        }

        #region IEnumerator Members

        public object Current
        {
            get
            {
                try
                {
                    return jobs[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public bool MoveNext()
        {
            position++;
            return (position < jobs.Length);
        }

        public void Reset()
        {
            position = -1;
        }

        #endregion
    }

Now consider another class Jobs. This class implements IEnumerable interface method GetEnumerator() returns IEnummerator object which holds indexed access to underlying array of Job objects as follows:

    class Jobs : IEnumerable
    {
        #region IEnumerable Members

        Job[] jobs;

        public Jobs(Job[] _jobsArray)
        {
            jobs = new Job[_jobsArray.Length];

            for (int i = 0; i < _jobsArray.Length; i++)
            {
                jobs[i] = _jobsArray[i];
            }
        }

        public IEnumerator GetEnumerator()
        {
            return new JobsList(jobs);
        }

        #endregion
    }

This is how now can use and manipulate our newly created IEnumerator object

        static void Main(string[] args)
        {
            // create new Job Array
            Job[] jobsArray = 
                 new Job[] { new Job("JobA", 1), new Job("JobB", 2), new Job("JobC", 3) };

            // // create new IEnumerable 
            Jobs jobs = new Jobs(jobsArray);

            // // create new IEnumerator
            IEnumerator jobsEnummerator = jobs.GetEnumerator();

            // following are some you can work over 
            // ways we can works over IEnumerator object
            while (jobsEnummerator.MoveNext())
            { }

            //  or using foreach
            foreach (Job job in jobs)
            { }
        }
Advertisements

Passing indefinite parameters as Method arguments in C#

One might have a situation where he or she needs to pass a number of variables as arguments at runtime. When we are sure of the parameters required, we can declare them in method signature, like

         public static void PrintMessage(string message, int times)
        {
            for (int i = 0; i < times; i++)
                Console.WriteLine(message);
        }

In the above example we know that we need a message as string and an int (times) which would be used to display the message a number of times. What if we do not know how many variables of some type or different types are required at compile time, like print a number of messages, together or message or names . Here is params keyword which will gracefully tackle this situation. If we need list of argument of particular type, like string

         public static void PringtMessages(params string[] stringsList)
        {
            foreach (string s in stringsList) { }   
            // your logic here
        }

        // this is how to call
        string[] messages = new string[] { "Message1", "Message2" };
        PringtMessages(messages);

This is how, if we a need to pass different type of objects as indefinite number of arguments

        public static void PrintMessageWithID(params object[] list)
        {
            foreach (string s in list) { } 
            // your logic here
        }
        object[] messageAndId = new object[] { "Message1", 1,  "Message2", 2 };
        PrintMessageWithID(messageAndId);