I use them to assign event handlers.
AddHandler SaveButton.Click, AddressOf MySaveRoutine
AddHandler MenuStripSaveButton.Click, AddressOf MySaveRoutine
This way, I can have one save routine that is not attached
to the buttons except by the events raised. Makes it
easier to maintain, and I can call the save routine
from anywhere else I want.
Here's another example:
Dim deleg as DisplayMessage
deleg = New DisplayMessage(AddressOf WriteToDebugWindow)
where OutputInformation looks like this:
Sub WriteToDebugWindow(ByVal msgText as String)
Debug.WriteLine(msgText)
End Sub
Then I can use this all over the place to invoke my
WriteToDebugWindow routine:
deleg.Invoke("You have an error here, the user pressed F2.")
deleg.Invoke("The user put in a date of 1888.")
deleg.Invoke("The user needs more training; " & _
"he keeps banging his head against the monitor.")
What if I want to change these to write to a flat file?
I can write a routine and call it, say WriteToFlatFile.
Then I can change the declaration of the delegate to this:
deleg = New DisplayMessage(AddressOf WriteToFlagFile).
And voila! All my messages get written out to a file
instead of printed on the debug line.
Francesco Balena has a keen example of using delegates
to do callback methods to print out the names of folders
inside folders, and use it to search for folders, etc.,
in his book "Programming Microsoft Visual Basic 2005:
The Language". This is the first place I read about
using delegates that really explained why I would
want to.
Robin S.