Chapter 4. Advanced C# Features
In this chapter, we cover advanced C# topics, including events, operator overloading, try statements and exceptions, attributes, unsafe code and pointers, preprocessor directives, and XML documentation.
Delegates
attributes? unsafe?access-modifier? new? delegate [ void |type]delegate-name(parameter-list);
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 ...