Datasheet
Strategy
x
11
The type constraint is still necessary, because the Database needs to return “null” in the event that
the search fails. But now at least the
Database is once again generic. Unfortunately, using it leaves
something to be desired:
class Program
{
static Database<Student> Students = new Database<Student>();
static Database<Instructor> Instructors =
new Database<Instructor>();
class SearchStudentsByName : ISearchCriteria<Student>
{
private string first;
private string last;
public SearchStudentsByName(string f, string l)
{
first = f;
last = l;
}
public bool Match(Student candidate)
{
return candidate.FirstName == first &&
candidate.LastName == last;
}
}
static void Main(string[] args)
{
// ...
Student s = null;
while (s == null)
{
Console.Write(“Please enter your first name:”);
string first = Console.ReadLine();
Console.Write(“\nPlease enter your last name:”);
string last = Console.ReadLine();
s = Students.Find(
new SearchStudentsByName(first, last));
if (s == null)
Console.WriteLine(“Sorry! Couldn’t find you”);
}
// Do something with s
Yikes. The code defi nitely got a little bit easier to use at the point of doing the search, but now a new
class has to be written every time a different kind of search needs to happen, and that class will have
to be accessible every place a search could be written.
Fortunately, the savvy C# 2.0 developer knows about delegates and their extremely powerful cous-
ins, anonymous methods. (Equally as fortunate, the savvy C# 2.0 developer knows not to shout
things out in a room full of people while reading a book.)
c01.indd 11c01.indd 11 10/1/2010 3:20:37 PM10/1/2010 3:20:37 PM