4.3 Delegates Versus Interfaces

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.



C# in a Nutshell
C # in a Nutshell, Second Edition
ISBN: 0596005261
EAN: 2147483647
Year: 2005
Pages: 963

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net