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.
Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.