Sep
27
2006
.NET 2.0 Collections with generics - the basics
Posted by admin under
.NET 2.0
I just created a simple tutorial on creating typesafe collections and adding (typesafe) sorting capabilities to it in .NET 1.x - now the time has come to .NET 2.0.
Some of the reasons at all for creating custom collections (instead of just using an ArrayList for example) 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, in .NET 2.0 - here's the easiest possible class and collection:
using System;
using System.Collections.Generic;
/// <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 LinkCollection : System.Collections.Generic.List<Link>
{
}
The link class is taken from our .NET 1.1 tutorial - and the only difference is the LinkCollection class. While technically - we still need to inherit a base class ( but not CollectionBase ) - and we still have to implement a certain interface - we can let the compiler generate that code for us - that's what generics are about.
The easiest way of understanding generics os to think like this: by specifying our inheritance from System.Collections.Generic.List<Link> the compiler is able to create typesafe functions (using class Link) for Add, IndexOf etc - without us needing to see it.
Now - all we need is to start using it - example of webform application:
private LinkCollection GetCollList()
{
LinkCollection oColl = new LinkCollection();
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);
return oColl;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = GetCollList();
Gridview1.DataBind();
}
}