Datasheet
It’s That Time of Year Again…
x
9
public Student Find(string first, string last)
{
foreach (Student i in data)
{
if (i.FirstName == first && i.LastName == last)
return i;
}
return null;
}
}
At fi rst glance, this seems like a good idea, but a longer look reveals that these two classes differ in
exactly one thing — the kind of data they “wrap.” In the fi rst case, it’s a list of
Instructors, and in
the second, a list of
Students.
The sharp C# 2.0 programmer immediately shouts out, “Generics!” and after enduring the quizzical
looks of the people sharing the room, looks to create a single type out of them, like this:
class Database<T>
{
private List<T> data = new List<T>();
public Database() { }
public void Add(T i) { data.Add(i); }
public T Find(string first, string last)
{
foreach (T i in data)
{
if (i.FirstName == first && i.LastName == last)
return i;
}
return null;
}
}
but unfortunately, the C# compiler will balk at the code in Find(), because the generic type T can’t
promise to have properties by the name of
FirstName and LastName. This can be solved by add-
ing a type constraint in the generic declaration to ensure that the type passed in to the
Database is
always something that inherits from
Person, and thus has the FirstName and LastName properties,
like this:
class Database<T> where T: Person
{
private List<T> data = new List<T>();
public Database() { }
public void Add(T i) { data.Add(i); }
public T Find(string first, string last)
{
foreach (T i in data)
{
if (i.FirstName == first && i.LastName == last)
return i;
}
c01.indd 9c01.indd 9 10/1/2010 3:20:37 PM10/1/2010 3:20:37 PM










