March 2002
Intermediate to advanced
864 pages
31h 8m
English
A problem that can be solved with a delegate can also be solved with
an interface. For instance, the following explains how to solve our filter problem
using an IFilter interface:
using System;
interface IFilter {
bool Filter(string s);
}
class Test {
class FirstHalfOfAlphabetFilter : IFilter {
public bool Filter(string s) {
return ("N".CompareTo(s) > 0);
}
}
static void Main() {
FirstHalfOfAlphabetFilter f = new FirstHalfOfAlphabetFilter();
Display(new string [] {"Ant", "Lion", "Yak"}, f);
}
static void Display(string[] names, IFilter f) {
int count = 0;
foreach (string s in names)
if (f.Filter(s))
Console.WriteLine("Item {0} is {1}", count++, s);
}
}In this case, the problem is slightly more elegantly handled with a delegate, but generally delegates are best used for event handling.