Jul
04
2004
Collections and sorting in C#
Posted by admin under
.NET
This article is intended for .NET 1.1. In version 2.0 I advise you to use generics instead of inheriting from CollectionBase - an article on that will be available (later) as well.
Some of the main goals when creating a custom collection (instead of just using for example ArrayList ) are
- type safety (you should only be able to insert objects of a certain type)
- incapsulation - you might for example create an ReadFromDatabase function inside the collection class
- still - we want to be able to use "regular" iterator functions - such as foreach etc
So - here the easiest possible class and collection:
using System;
using System.Data;
using System.Collections;
namespace colltest
{
/// <summary>
/// Summary description for Link.
/// </summary>
public class Link
{
private string m_strUrl = "";
private string m_strName = "";
public string Url
{
get
{
return m_strUrl;
}
set
{
m_strUrl = value;
}
}
public string Name
{
get
{
return m_strName;
}
set
{
m_strName = value;
}
}
public Link()
{
}
}
public class LinkColl : CollectionBase
{
public Link this[int nIndex]
{
get { return (Link) base.List[nIndex]; }
}
#region Methods
public void Add(Link tab)
{
//Kolla s den inte redan finns
base.List.Add(tab);
}
public int IndexOf(Link tab)
{
return base.List.IndexOf(tab);
}
#endregion
}
}
So the key for our collection class is to derive from CollectionBase. We then override
public Link this[int nIndex]
and
public void Add(Link tab)
and
public int IndexOf(Link tab)
and that's all we need. Now we are able to write code such as:
LinkColl oColl = new LinkColl();
Link oNew = new Link();
oNew.Name = "ASPCode";
oNew.Url = "http://www.aspcode.net";
oColl.Add( oNew );
oNew = new Link();
oNew.Name = "ASP.NET";
oNew.Url = "http://www.asp.net";
oColl.Add( oNew );
oNew = new Link();
oNew.Name = "411asp.net";
oNew.Url = "http://www.411asp.net";
oColl.Add( oNew );
foreach( Link oLink in oColl )
{
Console.WriteLine( oLink.Name + ":" + oLink.Url );
}
Download is available in part 4