2009-05-06

C# - Fun with .NET Generics, Lists.

If you've not yet experienced .NET Generics (part of the System.Collections namespace), you don't know what you're missing. This namespace is among the most valuable code within the .NET Framework (2.0+), and it's worth getting acquainted with. If you're stilling using arrays or ArrayLists, it's time to move on.

Getting started

It's time to familiarize yourself with List. List--an implementation of IList--is one of the most valuable additions to the .NET Framework. Use it in place of arrays or arraylists, when you can. Here's how to use it.

// Instantiate
List<int> Ids = new List<int>();

// Fill it with data
ids.Add(1);
ids.Add(7);
ids.Add(8);

// Iterate through it
foreach (int id in ids)
{
  Console.WriteLine(id);
}
// Output yields:
/*
1
7
8
*/

With the above sample, it gives you a good idea how to consume it. While I've used integers above, you can easily use any object, replacing <int> with <objecttype>. What makes this so amazing?

List<Employee> employees = new List<Employee>();
// Pretend there's code to populate your Employee List here.
foreach (Employee e in employees)
{
  Console.WriteLine(e.FirstName);
}
// Output yields:
/*
Employee1Name
Employee2Name
Employee3Name (etc.)
*/

Intellisense, too. None of that casting crap that goes along with ArrayLists--and you get the flexibility to dynamically add objects to a List, unlike arrays.

You can even create Classes that inherit from Lists. Use the following syntax.

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
}

Now, as you can imagine, this could have some amazing functions inside it like...

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
  public override bool Contains(Employee employee)
  {
    foreach (Employee e in this)
    {
      if (e.EmployeeID == employee.EmployeeID)
      {
         return true; 
      }
    }
    return false;
  }
}

You can even add custom Indexers as well.

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
  public virtual Employee this[Guid employeeID]
  {
    get
    {
      foreach (Employee e in this)
      { 
         if (e.EmployeeID = employeeID)
         {
            return e;
         }
      }
    }
    return null;
  }
}

Which can then be consumed like this...

EmployeeCollection ec = new EmployeeCollection();
// Pretend I've filled this List, too.
Guid employeeID; // pretend this is meaningfully filled.

Console.WriteLine(ec[employeeID].FirstName);
// Output yields:
// Employee5Name

Well. That's a brief introduction to the fun that you can have with the .NET System.Collections namespace. There's a whole lot more here. HashTables, Dictionaries, and Lists of all sorts. I'd recommend that you dig in to learn some more. Alas, Zoidberg Away!

No comments: