Creating a re-usable shopping basket with Generics in C#


We recently had troubles with our new reusable basket we’re developing at work.  We sell books, and most books come from one central data source which for the sake of this article i shall call CDS- so we have a CDS entities project which holds elements Group, Book, Author etc.  However not all of our sites run use the CDS for their data- so we have other projects with their own elements for Book, Author, Category etc which hold their own data.

We wanted to create a central project containing the basket functionality which we could drop into any project and use.  So the basket needs to be able to add lots of different types of books- some from the CDS entity library or some any other entity library we use.  To do this we created an Interfaces project which holds an interface called IBook which held the minimum data required by the basket such as Title, Price, ISBN, Cover Image.  This project is then referenced by the sites, the entity libraries (like CDS or any other’s we build) and the basket itself.

Adding the book to the basket was fine, however the problem arose when viewing items- the basket needed to be able to load the book data back- this is fine we thought- we would simply add a load() method to IBook, however this didnt solve the problem as the basket only had IBook signature of load- it didn’t know which concrete implementation of load to run.

The answer was to use generics.  We added a generic parameter to the top of the basket which accepted a type which it assumed to be derived from IBook and always have a default constructor, like so;

public class Basket<T> where T : Hachette.ProcessLayer.IBook, new() {
   private List<BasketItem<T>> _basket_items;
   ...
}

Likewise we made the basket item’s generic, and pass the type T from the basket to the basket item when instanciating them- the basket items are then able to define a real book instance of type T so it knows which concrete book it’s dealing with, so it can call the correct load method. The use of generics here means the basket object can reference a real book class from the CDS project (in a separate assembly) without having to reference that assembly, meaning we can drop in any type of book from any assembly for future sites, and with the parent website stating the type to use when creating the basket, the basket can remain completely independent.

  1. #1 by Paul on July 27, 2009 - 09:45

    You arse, stop using my Feeds to get higher ratings

  2. #2 by shawson on July 27, 2009 - 09:51

    Pah- Just because i get ranked higher in google for your content than you! I won’t stop till I have a #1 spot for “Paul Ledger”.

    Mwahahahahahahahaahahahaaaaaaa.

(will not be published)