Friday, May 9, 2008

ICollection & IEnumerator

ICollection inerface is used to make a custom collection type.
Function which must be used are - Add, Clear, Count, GetEnumerator
IEnumerator interface is used to enumerator through a collection.
Functions which must be used are - MoveNext, Current, Reset

The example below is the most basic and is used to create a string - string collection where each item in second list is dependent upon the item in the first list at the same index position.

Example

Collection class

public class CustomCollection : ICollection
{
List customMainList = new List();
List customDependentList = new List();


public virtual void Add(string x, string y)
{
customDependentList.Add(y);
customMainList.Add(x);
}

public virtual void Clear()
{
customMainList.Clear();
customDependentList.Clear();
}

#region ICollection Members

public void CopyTo(Array array, int index)
{
throw new Exception("The method or operation is not implemented.");
}

public int Count
{
get { return customMainList.Count; }
}

public bool IsSynchronized
{
get { throw new Exception("The method or operation is not implemented."); }
}

public object SyncRoot
{
get { throw new Exception("The method or operation is not implemented."); }
}

#endregion

#region IEnumerable Members

public IEnumerator GetEnumerator()
{
return new CustomCollectionEnumerator(customMainList, customDependentList);
}

#endregion
}


Enumerator for collection class

public class CustomCollectionEnumerator : IEnumerator
{
List customMainList = null;
List customDependent = null;
int position = -1;

public CustomCollectionEnumerator(List main, List dep)
{
customMainList = main;
customDependent = dep;
}

#region IEnumerator Members

public object Current
{
get { return new KeyValuePair(customMainList[position], customDependent[position]); }
}

public bool MoveNext()
{
position++;
return (position < customMainList.Count);
}

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

#endregion
}


Used in a program


CustomCollection cus = new CustomCollection();
cus.Add("wts1", "admin");
cus.Add("wts1", "suzie");
cus.Add("wts2", "admin");
cus.Add("wts3", "sally");
cus.Add("wts2", "dam");
foreach (KeyValuePair pair in cus)
{
Console.WriteLine(pair.Key + " : " + pair.Value);
}
Console.ReadKey();