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

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