Monday, 21 May 2007

Generic collection classes allow nulls

Something to bear in mind when using generic collections in .NET is that they allow you to add null into the collection for reference types. This is not a bug but it means that you need to be careful when iterating through the collection.

For example, if you had a collection declared as
Collection<Customer> customers = new Collection<Customer>();

then add a null into the collection like so:
customers.Add(null);

it adds a null reference into the collection. This means that customers.count returns 1 and all looks well, but this is not so good if you try to iterate around the collection like this:

foreach(Customer customer in customers)
{
customer.Firstname = "test";
}

You would get a null reference exception as the customer object in this case is null. This means you have to clutter your code with null checks as you iterate through the collection. Wouldn't it be nice if the .NET framework provided non-nullable generics collection classes? It's on my list to create a class that enables this. Watch this space.... :)

1 comment:

Anonymous said...

Of course one would ask why you weren't checking that null was being passed into the collection in the first place :)