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)
            { }
        }

Working with System.Collections.BitArray in C#

In the last post we have seen how to work with and ArrayList using C#. In this article I will explore the class BitArray and the methods provided.

BitArray class is designed to hold the values as bits. These values represent, either true or false. It is the simplest of collections and provides Bitwise operations like XOR, AND etc. The class is sealed and cannot be inherited and inherits from intefaces as follows,

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class BitArray : ICollection, 
    IEnumerable, ICloneable

class provides following constructors

           // Declare BitArray
            BitArray bitArray;

            // BitArray with 5 objects
            bitArray = new BitArray(5);  

            // constructor which takes a byte Array
            bitArray = new BitArray(new byte[3]);

            // constructor which takes a int Array          
            bitArray = new BitArray(new int[5] { 1, 2, 4, 5, 7 });

            // constructor which takes a number of 
            // bejts and default value to initialize with
            bitArray = new BitArray(5, true);

            // constructor which takes a bool Array
            bitArray = new BitArray(new bool[] { true, true, true, true, false });

Here are the remaining methods with usage sample

            // perform the And operation for this BitArray 
            // with another BitArray a return a new BitArray
            bitArray = bitArray.And(bitArray);

            // use cast to convert BitArray
            // to an Array of Type T
            string[] arrResult = bitArray.Cast<string>().ToArray<string>();

            // Copy item of a BitArray to another Array
            bitArray.CopyTo(new BitArray[5], 0);

            // count total items in a BitArray 
            int total = bitArray.Count;

            // compare BitArray with another Object
            bool IsEqualsTo = bitArray.Equals(new BitArray[5]);

            // get some value from  location
            bool somValue = bitArray.Get(0);

            // get an Enummerator 
            e = bitArray.GetEnumerator();
            while (e.MoveNext())
            {
                Object obj = e.Current;
            }

            // get Type of BitArray 
            Type type = bitArray.GetType();

            // check if is BitArray is read only
            bool IsReadOnly = bitArray.IsReadOnly;

            //  get the length of BitArray
            int length = bitArray.Length;

            //invert all teh items in BitArray
            bitArray = bitArray.Not();

            // perform Or operation with another BitArray
            // and return a new BitArray
            bitArray = bitArray.Or(bitArray);

            // set value at location
            bitArray.Set(0, true);

            // perform Xor operation with another BitArray
            // and return a new BitArray
            bitArray = bitArray.Xor(bitArray);

Working with System.Collections.ArrayList in C#

System.collections is an important and useful namespace which provides several classes and interfaces for the management of collections of different types. Of which IList, ArrayList, Hastable, IEnumerator and IComparer are a few to name. We can find these interfce and clases at the root of many classes found in later libraries released with later versions of .Net Framework. We will look into these classes and interfaces and where possible, try to see what methods are available and what can we do with them.

To start with, we will take ArrayList and see what it has to offer.

ArrayList is generally not recommended as it is not strongly typed and there are better options available, which we will discuss in later posts. ArrayList might only be be helpful if in case one is not sure of the type up-front for the collection.

ArrayList class provides three constructors, as follows

ArrayList arrayList;

// an empty constructor
arrayList = new ArrayList();

// constructor that takes another collection
arrayList = new ArrayList(new ArrayList());

// constructor which takes an int as initial capacity
arrayList = new ArrayList(0);

To Add Items To ArrayList:

// Add items in a ArrayList
arrayList.Add("one");
arrayList.Add(1);
arrayList.Add(true);

In code above you might have noticed that, different types of objects are assigned to same collection, making it prone to errors and adding over head for type checks and cast To and From Object while carrying out operation like

if(arrayList[0].GetType()== typeof(string))
{
   string valueAt0 = (string)arrayList[0];
}

Following are the remaining methods with usage samples

            // search in an ArrayList
            arrayList.BinarySearch("one");

            // get capacity of an ArrayList
            int listCapacity = arrayList.Capacity;

            // use Cast<T> to convert to another Collection
            List<string> list = arrayList.Cast<string>().ToList();

            // clear an Arraylist 
            arrayList.Clear();

            // Check if Arraylist contains an object
            arrayList.Contains("one");

            // copy the contents into an Array
            string[] tempArr = new string[3];
            arrayList.CopyTo(tempArr, 0);

            // get total number of items in ArrayList
            int numberOfItems = arrayList.Count;

            // get the index of an object in ArrayList
            arrayList.IndexOf("one");

            // Get and use IEnumerator from Arraylist
            IEnumerator e = arrayList.GetEnumerator();
            while (e.MoveNext())
            {
                Object obj = e.Current;
            }

            // get a new ArrayList from range of objects
            arrayList = arrayList.GetRange(0, 3);

            // get type 
            arrayList.GetType();

            // inset an object into ArrayList at a location:
            arrayList.Insert(0, "zero");

            // inset a range of objects into ArrayList at:
            arrayList.InsertRange(0, arrayList);

            // check , if Arraylist is of fixed size
            bool IsFixedSize = arrayList.IsFixedSize;

            // check , if Arraylist is read only
            bool IsReadOnly = arrayList.IsReadOnly;

            // remove an object 
            arrayList.Remove("one");

            // remove an object from index
            arrayList.RemoveAt(0);

            // sort ArrayList
            arrayList.Sort();

            // convert to an Array of Type T
            arrayList.ToArray(typeof(string));

            // get a string representation
            arrayList.ToString();