In your Visual Basic.NET journey, you have definitely encountered a well used but little understood phenomenon called a delegate. You use them everyday, but might not know it. In this article, we will take a look at what a delegate is and how it will help you to develop better software.
A delegate can be defined as a type safe function pointer. It encapsulates the memory address of a function in your code. Whenever you create or use an event in code, you are using a delegate. When the event is thrown, the framework examines the delegate behind the event and then calls the function that the delegate points to. As we will see later, delegates can be combined to form groups of functions that can be called together.
Let's first take a quick look at how to define and invoke a delegate. First we declare our delegate in our form class:
Private Delegate Sub MyDelSub()
Then we use the delegate by simply declaring a variable of the delegate and assigning the sub or function to run when called. First the sub to be called:
Private Sub WriteToDebug()
Debug.WriteLine( "Delegate Wrote To Debug Window" )
You will notice also that it matches our declaration of
MyDelSub; it's a sub routine with no parameters. And then our test code:
Dim del As MyDelSub
del = New MyDelSub(AddressOf WriteToDebug)
When we invoke the delegate, the
WriteToDebug sub is run. Visual Basic hides most of the implementation of delegates when you use events, which are based off invoking a delegate. This is the equivalent of the above delegate invoke also.
Private Event MyEvent() 'declare it in the class
'to use it, add a handler and raise the event.
AddHandler MyEvent, AddressOf WriteToDebug
If delegates stopped at this point, they would be useless since events are less work and do the same thing. Let's get into some of the more advanced features of delegates. We will start with multicast delegates.