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
Greate a new Solution in Visual Studio. Name the new solution "GenericCatalog"
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; }
Create a simple model class like Student. This class must implement the interface IIdentifiable.
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
default(TElement)
is no such element existsUse a IList (implemented as a List) to hold the elements in Catalog.
Make a unit test to test the Catalog class. Use your simple model class in the test.
Model classes migh need different types of ID's
To include that we must make the interface IIdentifiable generic:
public interface IIdentifiable<TId> { ... }
Adapt you model class to this change.
Make at least one other model class (like Book) that uses another type of Id.
Adapt the Catalog class to include the changes in the interface IIdentifiable
public class Catalog<TId, TElement> where TElement : IIdentifiable<TId> { ... }
Adapt the test to run with the new version of the Catalog class.
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> { ... }