Wednesday, October 22, 2008

How to create a collection of classes in .net

To create a collection, capable of:

being used in a foreach loop,
being returned from a webmethod

etc, you need to create a class that inherits CollectionBase and iEnumerable.

Both of these classes require you implement several methods, and you also need to create an Enumerator class, see the code below and put your class in instead.

Note the default following: public OrderLine this[int i]{...} is required to automatically return each element of the collection when used as a return value for a webmethod.



using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace OfficeOps.SalesOrdering.SalesOrder
{
public class OrderLines : CollectionBase, IEnumerable
{

public void Add(OrderLine ordLine)
{
List.Add(ordLine);
}
public void Remove(int index)
{
if (index > Count - 1 || index < 0)
{
throw new Exception("Index out of bounds");
}
List.RemoveAt(index);
}

public OrderLine this[int i]
{
get { return (OrderLine)List[i]; }
}
public class OrderLineEnumerator : IEnumerator
{
int nIndex;
OrderLines collection;
public OrderLineEnumerator(OrderLines coll)
{
collection = coll;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return (nIndex < collection.Count);
}
public OrderLine Current
{
get
{
return ((OrderLine)collection[nIndex]);
}
}
object IEnumerator.Current
{
get
{
return (Current);
}
}
}
public new OrderLineEnumerator GetEnumerator()
{
return new OrderLineEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

}

}

No comments: