T, Earl Grey, Hot: Generics in .NET presented by JeremyBytes.com
©Jeremy Clark 2012 Page 9
a reference placed on the stack. When we cast the object back to a value type, it is “unboxed”,
meaning that the value is pulled off the heap and placed into the stack.
This process of boxing and unboxing incurs some overhead. If we use an ArrayList (or other non-
generic collection) to store value types (such as integers or other numeric types), each time we place a
value into the list, it is boxed; and each time we pull a value from the list, it is unboxed. For collections
with many members, the result is that a large percentage of the processing time is spent on the
boxing/unboxing procedure.
When we use a generic collection with a value type (such as List<int>), we do not have to go through
the boxing/unboxing process. The result is that generic collections of value types run much more
efficiently than their non-generic counterparts.
Reuse and Extensibility
So, we’ve seen how generics can add type-safety to our code. This helps us catch errors at compile-time
instead of runtime and makes our code more robust. So far, we have just used classes that are built into
the .NET BCL. We can use generics in our own classes to get the same advantages. Today, we’ll look at
how generics can help with reuse and extensibility.
The Repository Pattern
If you’re writing business applications, you probably have a mechanism set up for CRUD (Create, Read,
Update, Delete) operations. The Repository Pattern allows us to build a common interface for these
operations so that our application is not tightly coupled to the underlying data store. If you want more
information on the Repository Pattern and using it to create different repositories (for a SQL database, a
CSV file, and a web service), see “IEnumerable, ISaveable, IDontGetIt: Understanding .NET Interfaces”
(available for download here: http://www.jeremybytes.com/Downloads.aspx#INT).
To take a look at generics, we’ll use the repository pattern, but we’ll restrict ourselves to a single
implementation for simplicity.
A Person Repository
In the Generics.Common project, we have a folder for interfaces. Let’s take a look at
IPersonRepository to see how the repository pattern works.
public interface IPersonRepository
{
IEnumerable<Person> GetPeople();
Person GetPerson(string lastName);
void AddPerson(Person newPerson);
void UpdatePerson(string lastName, Person updatedPerson);
void DeletePerson(string lastName);