Delegates
A delegate is a type defining a method signature, so that delegate instances can hold and invoke a method or list of methods that match its signature. A delegate declaration consists of a name and a method signature. For example:
using System;
delegate bool Filter (string s);
class Test {
static void Main( ) {
Filter f = new Filter(FirstHalfOfAlphabet);
Display(new String [ ] {"Ant","Lion","Yak"}, f);
}
static bool FirstHalfOfAlphabet(string s) {
return "N".CompareTo(s) > 0;
}
static void Display(string[ ] names, Filter f) {
int count = 0;
foreach(string s in names)
if(f(s)) // invoke delegate
Console.WriteLine("Item {0} is {1}", count++,
s);
}
}Note that the signature of a delegate method includes its return
type. It also allows the use of a
params
modifier in its parameter list, which
expands the list of elements that characterize an ordinary method
signature. The actual name of the target method is irrelevant to the
delegate.
Multicast Delegates
Delegates can hold and invoke multiple methods.
In this example, we declare a very simple delegate called
MethodInvoker, which we use to hold and then
invoke the Foo and Goo methods
sequentially. The +=
method creates a new
delegate by adding the right delegate operand to the left delegate
operand:
using System; delegate void MethodInvoker( ); class Test { static void Main( ) { new Test( ); // prints "Foo","Goo" } Test ( ) { MethodInvoker m = null; m += new MethodInvoker(Foo); m += new MethodInvoker(Goo); m( ); } void Foo( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access