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 inFileSystemWatcher
. 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
System.Delegate
. InFileSystemWatcher
, then,FileSystemEventHandler
is an implicit subclass ofSystem.Delegate
.
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
FileSystemEventHandler
and use the+=
operator to add it to each of theFileSystemWatcher
‘sFileSystemEventHandler
events.
[The code that does this is:
FileSystemEventHandler onFileSystemEvent = new FileSystemEventHandler (OnFileSystemEvent);
where 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.