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

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
                return _count;

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

               return (_count - 1);
                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;
            return inList;

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

        // Overriding ToString() Method
        public override string ToString()
            StringBuilder sb = new StringBuilder();
            foreach (object o in _contents)
            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]
                throw new NotImplementedException();
                throw new NotImplementedException();

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

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

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.

public class Stack : ICollection, IEnumerable, 

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
            // remove from stack

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

            // check if Stack contains an object

            // 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

            // convert to an Array of Type T

            // get a string representation

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.

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 =

            // check if SortedList contains a key

            // check if SortedList contains a key

            // check if SortedList contains a value

            // 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;

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

            // get Key at index;

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

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

            // get index of an Item by key

            // get index of an Item by value

            // 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:
            // remove an item at:

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

Working with Arrays in C#

This Post will look in to several Methods provided with arrays.

There are several ways to declare and initialize an array

  // ways  to declare and initialize an Array

DateTime[] dt = new DateTime[2];
DateTime[] dt2 = new DateTime[2] { new DateTime(), new DateTime() };
DateTime[] dt3 = new DateTime[] { new DateTime(), new DateTime() };
DateTime[] dt4 = { new DateTime(), new DateTime() };

we will take a character array and see what can we do with its methods

like the above sample we can declare our character array using following syntax.

char[] charArr =
    { 'c', 'o', 'd', 'i', 'g', 'p', 'h', 'o', 'b', 'i', 'a' };

Here are some of the built-in methods

           // Get the Length of array, takes 
           // dimension and returns and int
            Console.WriteLine("Length of Array is {0}", charArr.GetLength(0));

            // Get the length of array, takes 
            // dimension and returns and long
            Console.WriteLine("Length of Array is {0}", charArr.GetLongLength(0));

            // Get the dimensio  od the array, o in
            // for single dimension as for this case
            Console.WriteLine("Array has {0} dimensions", charArr.Rank);

            // Get the type of array, whic in this
            // case is System.Char[] 
            Console.WriteLine("Type of Array is : {0}", charArr.GetType());

            // Get the Lowe Bound for the Array
            Console.WriteLine("Lower bound for the array = {0}", charArr.GetLowerBound(0));

            // Get the upper bound for the Array
            Console.WriteLine("Upper bound for the array = {0}", charArr.GetUpperBound(0));

            // Get  the calue at value '0'
            Console.WriteLine("Value at 0 location is {0} ", charArr.GetValue(0));

            // initialize Array
            Console.WriteLine("Initializing Array"); charArr.Initialize();

            // check is the Array is of Fixed size
            Console.WriteLine("is Array of fixed size: {0}", charArr.IsFixedSize);

            // check is the array is read only
            Console.WriteLine("is Array read only: {0}", charArr.IsReadOnly);

            // Get a new string from the Array
            // using constructor. copy from index 0 
            // next 5 items
            string value = new string(charArr, 0, 5);

            // Get  the string representation of Array
            value = charArr.ToString();
            // Set value to 'j' at location '0'
            charArr.SetValue('j', 0);

            // Copy array to another Aray. size of the
            // destination Array must >= from Array
            charArr.CopyTo(new char[30], 0);

            // Compare Array to another Object
            charArr.Equals(" ");

            // Get hashcode for the Array
            Console.WriteLine("Hash Code of Array is {0}", charArr.GetHashCode());