My friend Nick dashed off the following quick reply to my previous screed (in its first incarnation as an email message to him):
I think it’s the difference between thinking of it as a verb or a noun.
That would be fine, except they’re using it as a noun. Allow me to quote from Dumbill and Bornstein:
These methods [such as
OnFileSystemEvent, which will be referred to later] must match the delegates declared in
FileSystemWatcher. From the Mono FileSystemEventHandler.cs […] source file […]:
public delegate void FileSystemEventHandler (object sender, FileSystemEventArgs e);
A delegate declaration defines an instance of a class descended from
FileSystemEventHandleris an implicit subclass of
So it looks like a function declaration, but it’s really a subclass declaration? (I presume “instance of a class” doesn’t mean “an object that belongs to a class” here.)
… Next, we construct a new delegate of type
FileSystemEventHandlerand use the
+=operator to add it to each of the
[The code that does this is:
FileSystemEventHandler onFileSystemEvent = new FileSystemEventHandler (OnFileSystemEvent);
OnFileSystemEvent was previously declared as a static method with a signature matching the one above.]
So what we appear to have is a declaration that looks like a function but really declares a subclass of a special type of object that has only one method and no instance variables. Then you create one of these — things — initializing it with a matching method, and finally attach it to another object in a special way, such that it will be called back when a particular — something — happens.
I’m not saying this isn’t useful, but couldn’t they have presented it a different way, or called it something different (“callback”)?
Maybe I’m putting the blame in the wrong place. The philosophy of the Developer’s Notebook series seems to be to get you writing code quickly, and eschew all the theory. (They even title this section “Define Function Pointers”.) Perhaps I should crack open Hejlsberg et al. and see if they explain it more precisely.