Recent Entries:


List Management with Generic List in .NET

Monday, June 12th, 2006

I work with collections of objects very frequently and with version 1.1 of the Framework I would normally use the ArrayList class to manage them. With an ArrayList you are able to hold a collection of just about any type of object but there is no help with type safety. In version 2.0 of the Framework we are able to use Generics which allow us to realize type safety at compile time. Generics allow you to create a data structure without committing to a specific data type. Generics provide type safety but without any loss of performance or code bloat.

I now use the List class to manage my read-only lists. List represents a strongly typed list of objects that can be accessed through an index. List also provides methods to search, sort, and manipulate a collection of objects. Here is simple example of List usage:

using System.Collections.Generic;

List<Book> books = new List<Book>();
Book b = new Book();
b.Author = “Anthony Bourdain”;
b.Title = “Kitchen Confidential”;
b.NumberPages = 300;
books.Add(b);

b = new Book();
b.Author = “George Orwell”;
b.Title = “1984″;
b.NumberPages = 200;
books.Add(b);

foreach (Book book in books)
{
Console.WriteLine(book.Title);
}

List implements the IList interface which is the minimum interface required to implement a binding-capable list data source. Therefore you can bind a List as a non-editable data source. Using our previous example we can now bind this list to a data source.

Repeater1.DataSource = books;
Repeater1.DataBind();

I recommend dumping the usage of ArrayList and refactoring your code to utilize the List class.

2 Responses to “List Management with Generic List in .NET”

  1. Darrin Says:

    At first I wasn’t sure of the point of Generics, but now there are almost a staple. It saves me a lot in the way of run-time debugging and the ability to catch and handle wrong-type assignments.

    Nice post Money…

  2. Hierarchies with Nested Repeaters in .NET Says:

    […] of fussing with clumsy DataReaders or DataSets. Posted in ASP.NET, Engineering | Trackback | del.icio.us | Top OfPage […]

Leave a Reply