Exercise: Generic Catalog

In this exercise you are going to create a generic Catalog.

Since the Catalog is generic it can be used with (almost) all kinds of objects

Getting started

Greate a new Solution in Visual Studio. Name the new solution "GenericCatalog"

Simple interface IIdentifiable

To make the generic Catalog work you must first define a very simple interface IIdentifiable (note the double I's - the first I is due to the C# naming convention: Names of interfaces be prefixed 'I')

The interface IIdentifiable is NOT be generic (at least not until later on in this exercise). IIdentifiable must declare a single property. The property is read-only (only get, not set)

     int Id { get; }

Model class implementing IIdentifiable

Create a simple model class like Student. This class must implement the interface IIdentifiable.

Class Catalog<T>

Create a class Catalog. The class must be generic

     public class Catalog<TElement> where TElement: IIdentifiable { ... }

Catalog has a single type parameters:

The class must have methods like

Use a IList (implemented as a List) to hold the elements in Catalog.

Unit testing

Make a unit test to test the Catalog class. Use your simple model class in the test.

Generic interface IIdentifiable

Model classes migh need different types of ID's

To include that we must make the interface IIdentifiable generic:

     public interface IIdentifiable<TId> { ... }

Model class

Adapt you model class to this change.

Make at least one other model class (like Book) that uses another type of Id.

Catalog Class

Adapt the Catalog class to include the changes in the interface IIdentifiable

     public class Catalog<TId, TElement> where TElement : IIdentifiable<TId> { ... }

Unit testing

Adapt the test to run with the new version of the Catalog class.

Extra: Generic model classes

Now we will take generics one step further - some would say one step to far!

The model classes should be generic, example

class Book<TId> : Identifiable<TId> { ... }