Implement System.Collections.IList Interface using C#

Today we will look into the interface System.Collections.IList and some of the its methods. A very good example is for IList implementation in use any class Inheriting from IList or ArraList class itself. Following is ArrayList Signature as on MSDN.

public class ArrayList : IList, ICollection, IEnumerable, ICloneable

To start with, let’s derive a simple class from IList

public class ListImpl : IList
{ 
 private object[] _contents = new object[8];
}

We need to implement all members defined in the IList interface and and the interfaces: ICollection and IEnumerable as IList derives from these interfaces. Following is CopyTo Method from ICollection interface.

        public void CopyTo(Array array, int index)
        {
            int j = index;
            for (int i = 0; i < Count; i++)
            {
                array.SetValue(_contents[i], j);
                j++;
            }
        }

Following is GetEnumerator method from IEnumerable interface.

public IEnumerator GetEnumerator()
{
  // Refer to the IEnumerator documentation another sample
  return (_contents as IEnumerable).GetEnumerator();
}

Here are some other methods and properties

      private int _count;
      public int Count
      {
            get
            {
                return _count;
            }
       }

       // Add an object to the List
       public int Add(object value)
       {
           if (_count < _contents.Length)
           {
               _contents[_count] = value;
               _count++;

               return (_count - 1);
           }
           else
           {
                return -1;
           }
       }

       // Clear the List
       public void Clear()
        {
            _count = 0;
        }

       // Check if the List contains some value
       public bool Contains(object value)
        {
            bool inList = false;
            for (int i = 0; i < Count; i++)
            {
                if (_contents[i] == value)
                {
                    inList = true;
                    break;
                }
            }
            return inList;
        }

       // Check if List is fixed size
       public bool IsFixedSize
        {
            get
            {
                return true;
            }
        }

        // Overriding ToString() Method
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (object o in _contents)
            {
                sb.Append(o.ToString());
            }
            return sb.ToString();
        }

We need to provide implementation for following methods as per requirements.


        public int IndexOf(object value)
        {
            throw new NotImplementedException();
        }

        public void Insert(int index, object value)
        {
            throw new NotImplementedException();
        }

        public bool IsReadOnly
        {
            get { throw new NotImplementedException(); }
        }

        public void Remove(object value)
        {
            throw new NotImplementedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        public object this[int index]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool IsSynchronized
        {
            get { throw new NotImplementedException(); }
        }

        public object SyncRoot
        {
            get { throw new NotImplementedException(); }
        }
Advertisements

Working with System.Collections.Stack in C#

In the last post, Working with System.Collections.Queue, we have seen how to work with Queue using C#. In this article I will explore Stack class and the methods provided.

Stack, is a simple class which represents last-in, first-out collection (L-I-F-O) of objects and behaves exactly like, any stack in normal life should behave.

Here is class signature as at MSDN.

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

Here is how to declare and initialize Stack

           // Dclare Stack
            Stack stack;

            // initiatlize with a collection
            stack = new Stack(new int[3] { 1, 2, 3 });

            // initiatlize with initial capacity 
            stack = new Stack(10);

            // default initialization
            stack = new Stack();

Here is how we can add and remove items from stack. Remember, we can add items at the end and the very last item could be returned or removed. This means that we cannot remove other than the last entry. We can thogh, remove all items at once, we will see how.

           // insert into stack
            stack.Push(6);
            
            // remove from stack
            stack.Pop();

Here are the remaining methods and a bit of details for how to use them.

           // Return an Object at the end (Last input), without removing
            object value = stack.Peek();

            // filter and get item as per type from Stack
            IEnumerable queueEnummerable = stack.OfType<string>();

            // compare with another object
            bool IsEqualTo = stack.Equals(stack);

            // get an instance of type IQueryable
            IQueryable querable = stack.AsQueryable();

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

            // clear a Stack, remove all items
            stack.Clear();

            // check if Stack contains an object
            stack.Contains("one");

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

            // get total number of items in Stack
            int numberOfItems = stack.Count;

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

            // get type
            stack.GetType();

            // convert to an Array of Type T
            stack.ToArray();

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

Working with System.Collections.Queue in C#

In the last post, Working with System.Collections.SortedList, we have seen how to work with SortedList using C#. In this article I will explore Queue class and the methods provided.

Queue, is a simple class which represents first-in, first-out collection of objects and behaves exactly like, any queue in normal life should behave.

Here is class signature as at MSDN.

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

Here is how we can declare and initialize a Queue object

            // declare Queue
            Queue queue;

            // initiatlize with initial capacity 
            queue = new Queue(10);

            // initiatlize with initial capacity 
            // and grow factor
            queue = new Queue(10, 5);

            // initiatlize with a collection
            queue = new Queue(new String[5]);

            // default initialization
            queue = new Queue();

This is how to add am object to a Queue. An object could be added to the end only

 // Add an object to the tail
queue.Enqueue("");

This is how to remove an object from a Queue. An object could be removed from front only

 // remove an object from front
 queue.Dequeue();

Here are remaining methods provided with a bit of details for what they can do for us

            // Return an Object at the front, // without removing
            object value = queue.Peek();

            // filter and get item as per type from Queue
            IEnumerable queueEnummerable = queue.OfType<string>();

            // compare with another object
            bool IsEqualTo = queue.Equals(queue);

            // get an instance of type IQquerable
            IQueryable querable = queue.AsQueryable();

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

            // clear an Queue
            queue.Clear();

            // Check if Queue contains an object
            queue.Contains("one");

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

            // get total number of items in Queue
            int numberOfItems = queue.Count;

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

            // get type
            queue.GetType();

            // convert to an Array of Type T
            queue.ToArray();

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

Working with System.Collections.SortedList in C#

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

SortedList class is designed to hold the objects in key/value pairs. These can be accessed using key or by index, if known.

Here is class signature as at MSDN.

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class SortedList : IDictionary, ICollection, 
    IEnumerable, ICloneable

Here is explanation of the constructors provided and how to use them

            // Declare SortedList
            SortedList sortedList;

            // constructor which takes Comparer          
            sortedList = new SortedList(new Comparer(CultureInfo.CurrentCulture));

            // constructor which takes Dictionary 
            sortedList = new SortedList(new Dictionary<int, string>());

            // constructor which takes initial capacity
            sortedList = new SortedList(5);

            // constructor which takes Comparer and initial capacity
            sortedList = new SortedList(new Comparer(CultureInfo.CurrentCulture), 5);

            // constructor with Dictionary and Comparer 
            sortedList =
                new SortedList(new Dictionary<int, string>(), new Comparer(CultureInfo.CurrentUICulture));
            
            // Default empty constructor 
            sortedList = new SortedList();

Items could be added in the combination of key/Value Pairs

            // Add Items as key value pairs
            sortedList.Add(1, "one");
            sortedList.Add(2, "two");
            sortedList.Add(3, "three");

Here are rest of the methods and how to use them

           // get size of SortedList
            int size = sortedList.Capacity;

            // convert to string[] Array using Cast<T>
            // and ToArray()
            string[] stringArray =
                sortedList.Cast<string>().ToArray<string>();

            // check if SortedList contains a key
            sortedList.Contains(1);

            // check if SortedList contains a key
            sortedList.ContainsKey(1);

            // check if SortedList contains a value
            sortedList.ContainsValue("one");

            // copy SortedList To  an Array
            sortedList.CopyTo(new string[5], 0);

            // get total Item count in SortedList 
            int totalItems = sortedList.Count;

            // check if SortedList is == another object
            sortedList.Equals(new SortedList());

            // get item at index;
            sortedList.GetByIndex(0);

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

            // get Key at index;
            sortedList.GetKey(0);

            // get Keys as IList
            IList keyList = sortedList.GetKeyList();

            // get Values as IList
            IList valueList = sortedList.GetValueList();

            // get index of an Item by key
            sortedList.IndexOfKey(1);

            // get index of an Item by value
            sortedList.IndexOfValue("one");

            // check if SortedList is of Fixed Size 
            bool IsFixedSize = sortedList.IsFixedSize;

            // check if SortedList is Read Only
            bool IsReadOnly = sortedList.IsReadOnly;

            // get Keys as ICollection
            ICollection keysCollection = sortedList.Keys;

            // get Values as ICollection
            ICollection valuesCollection = sortedList.Values;

            // get items as filtered IEnumerable of Type T
            IEnumerable filteredList = sortedList.OfType<string>();

            // remove an item:
            sortedList.Remove("one");
            
            // remove an item at:
            sortedList.RemoveAt(0);

            // set an item at index:
            sortedList.SetByIndex(5, "one");

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();