Delegates

If you are comfortable working with methods (Sub Procedures and Functions) in Visual Basic, then you should have no problem understanding the concept of Delegates.

Delegates are basically pointers to methods that have the exact same signature (or “shape”) as the method they point to.  They are strongly-typed, and can be invoked (or “called”) at any time.  Delegates can point to 1 method, or multiple methods, and can be invoked either synchronously or asynchronously.

In the .NET Framework, there are many place where Delegates are used.  Examples include generic lists (System.Collections.Generic.List(Of Type)) which have Sort and Find methods that use them, every Event uses a Delegate (for example, a “button_click()” event), and the new LINQ architecture uses them extensively.

There are three pieces of information that are maintained by a Delegate, and they are:  The address (or name) of the method they are pointing to, the arguments that are passed to the method, and the return type of the method (if there is one).

To create a Delegate, you must declare it at the Member (class) level, using the Delegate Keyword.  Additionally, you must specify whether the Delegate is going to point to a Sub Procedure or a Function.  Just like any variable, you can name the Delegate whatever you want. And as mentioned, you must define the signature of the Delegate (including parameters and return type).

Here’s an introductory example of creating a Delegate that will point to a Sub Procedure with no parameters:

 

Private Delegate Sub PrintHelloWorldDelegate()


As mentioned, this Delegate can be used to point to any Sub Procedure that has no arguments.  Here is an example:

 

Private Sub PrintHelloWorld()

    Console.WriteLine("Hello World!")

End Sub

 

As a note, the method that the delegate is pointing to does not have to have the same (or similar) name as the delegate, and the delegate can point to any method that has the exact same signature as the delegate (which is a Sub Procedure with no arguments in this case).

To use a Delegate, you have to create a variable that is of the delegate type, which in this case is the “PrintHelloWorldDelegate” delegate type, and tell it what method it is going to “point to”.  To demonstrate this, we will add a new method called “Print”, which will be called to perform the printing.

 

'This sub will be called to print "Hello World!"
Public Sub Print()

    'Declare the "printDelegate" variable as the
    '  PrintHelloWorldDelegate type.
    '  This means that the printDelegate variable
    '  will point to a Sub Procedure that has no
    '  arguments, no return type
    Dim printDelegate As PrintHelloWorldDelegate

    'Create a new instance of the Delegate, and
    '  assign it the address of the
    '  "PrintHelloWorld" Sub Procedure.
    '
    '  Basically, we are telling the "printDelegate"
    '  variable to call the "PrintHelloWorld" Sub
    '  Procedure when it is invoked.
    printDelegate = New PrintHelloWorldDelegate( _
        AddressOf PrintHelloWorld)

    'Now, we can invoke (call) the "PrintHelloWorld"
    '  Sub Procedure that the delegate points to.
    printDelegate()

    'Invoking the delegate produces the exact same
    '  result as if we called the Sub Procedure
    '  explicitly.
    PrintHelloWorld()

End Sub

 

The complete class now looks like this:

 

Public Class WorkingWithDelegates

    'Declare a Delegate at the member (class) level
    '  that will point to a Sub Procedure,
    '  and that has no parameters, no return type
    Private Delegate Sub PrintHelloWorldDelegate()

    'This is the Sub Procedure that the Delegate
    '  will point to (it doesn't point to it yet)
    Private Sub PrintHelloWorld()

        'Print to the Output Window
        Console.WriteLine("Hello World!")

    End Sub


    'This sub will be called to print "Hello World!"
    Public Sub Print()

        'Declare the "printDelegate" variable as
        '  the PrintHelloWorldDelegate type.
        '  This means that the printDelegate
        '  variable will point to a Sub Procedure
        ' that has no arguments, no return type
        Dim printDelegate As PrintHelloWorldDelegate

        'Create a new instance of the Delegate,
        '  and assign it the address of the
        '  "PrintHelloWorld" Sub Procedure.
        '
        '  Basically, we are telling the
        '  "printDelegate" variable to call the
        '  "PrintHelloWorld" Sub Procedure when it
        ' is invoked.
        printDelegate = _
            New PrintHelloWorldDelegate( _
            AddressOf PrintHelloWorld)

        'Now we can invoke (call) the
        '  "PrintHelloWorld" Sub Procedure that
        '  the delegate points to.
        printDelegate()

        'Invoking the delegate produces the exact
        '  same result as if we called the Sub
        '  Procedure explicitly.
        PrintHelloWorld()

    End Sub

End
Class

 

 

Delegates with Parameters

 

As mentioned, Delegates can point to methods that have parameters.  But in order for Delegates to be able to point to methods that have parameters, they must be declared with the exact same list of parameters that the method they are going to point to has.

 

As an example, here is a delegate that will point to a Sub Procedure that has 1 String parameter:

 

'Create a Delegate that will point to a Sub
'  Procedure that has 1 String parameter.
Private Delegate Sub _
    PrintStringDelegate(ByVal text As String)

'The PrintStringDelegate above can be used
'  to point to a Sub Procedure like this:
Private Sub PrintString(ByVal text As String)

    'Print to Output Window
    Console.WriteLine(text)

End Sub

 

To use PrintStringDelegate in the example above, we need to create a variable of the PrintStringDelegate type, and assign it the address of the PrintString Sub Procedure, then invoke (call) it.

 

'Create a new instance of the PrintStringDelegate
' and tell it to "point to" the PrintString
'  Sub Procedure
Dim printStrDelegate As _
    New PrintStringDelegate(AddressOf PrintString)

'Invoke (call) the "PrintString" Sub Procedure
'  that the delegate points to.

printStrDelegate("Hello World!")

 

 

Here is another example of a delegate that will point to a Sub Procedure that has 1 Integer parameter:

 

'Create a Delegate that will point to a Sub
'  Procedure that has 1 Integer parameter
Private Delegate Sub _
    PrintNumberDelegate(ByVal number As Integer)

'The PrintNumberDelegate above can be used to point
'  to a Sub Procedure like this:
Private Sub PrintNumber(ByVal number As Integer)

    'Print to Output Window
    Console.WriteLine(number)

End Sub

 

And again, an example of how to invoke (call) it:

 

'Create a new instance of the printIntDelegate
' and tell it to "point to" the PrintNumber
'  Sub Procedure
Dim printIntDelegate As _
    New PrintStringDelegate(AddressOf PrintNumber)

'Invoke (call) the "PrintString" Sub Procedure
'  that the delegate points to.

printIntDelegate(123)

 

 

Remember that Delegates can take any number of parameters, they are not just limited to 1.  So let’s take a look at a Delegate that has multiple parameters:

 

'Create a Delegate that will point to a Sub
'  Procedure with 3 arguments
Private Delegate Sub PrintNameDelegate( _
                    ByVal firstName As String, _
                    ByVal lastName As String, _
                    ByVal website As String)


'The PrintNameDelegate above can be used to point
'  to a Sub like this:
Private Sub PrintName(ByVal firstName As String, _
                      ByVal lastName As String, _
                      ByVal website As String)

    'Print to Output Window
    Console.WriteLine("{0} {1}", _
        firstName, lastName)

    Console.WriteLine("blog:  {0}", website)

End Sub

 

And again, here’s an example of how to invoke (call) it:

 

'Create a new instance of the PrintNameDelegate
' and tell it to "point to" the PrintName
'  Sub Procedure
Dim printDelegate As New  _
    PrintNameDelegate(AddressOf PrintName)

'Invoke (call) the PrintName Sub Procedure that
'  the printDelegate is pointing to.

printDelegate("Gary", "Lima", _
        "http://garylima.blogspot.com/")

 

So all that is pretty simple?  Ok, let’s take a look at working with Delegates that have return types.

 

 

Delegates with Parameters and Return Types

 

So far we’ve been working with Delegates that do not have Return Types.  These Delegates have been declared using the “Sub” keyword.  To create a Delegate that has a Return Type, use the “Function” keyword instead.  And, just like a function, add the Return Type at the end of the declaration.

 

Here’s an example of a delegate that will point to a Function that will add 2 Integers together and return an Integer as a result:

 

'Create a Delegate that will point to a Function
'  that takes 2 Integer arguments, and returns
'  an Integer
Private Delegate Function AddDelegate( _
    ByVal x As Integer, ByVal y As Integer) _
    As Integer

'The AddDelegate above can be used to point to
'  a Function like this:
Private Function Add(ByVal x As Integer, _
    ByVal y As Integer) As Integer

    'Add x + y and return the value
    Return x + y

End Function

 

And here’s an example of how to invoke it:

 

'Create a new instance of the AddDelegate
'  and tell it to "point to" the Add Function
Dim adDelegate As New AddDelegate(AddressOf Add)

'Invoke the Add Function that the AddDelegate
'  points to, and get the result
Dim result As Integer
result = adDelegate(2, 2)

'Print to Output Window
Console.WriteLine("The result is {0}", result)

 

Remember that a Function Delegate does not have to have parameters, but it does have to have a Return Type.  The parameters do not have to be of the same type as each other, or as the Return Type.

 

Ok, so now that we’ve had a chance to look at Delegates, including their parameters and return types, let’s take a look at some examples of using Delegates.

 

 

Event Handling with Delegates

 

The .NET Framework has a generic collection list class called “List(Of Type)” that can be used to store any type of object.  Although the list is generic, it is a strongly-typed list that will only store objects of the declared type.  So, if you declare your list as “List(Of String)” the list will only store Strings, if you declare you list as “List(Of Integer)” the list will only store Integers, and so on.

 

Because this type of collection list is so useful for storing objects, it makes it a perfect candidate for inheritance.  A derived class can be created, and programmed with a Delegate to provide “call back” event notification to let the caller receive feedback on the status of items that have been added to the list.

 

The concept of a “call back” delegate is pretty simple.  In the easiest since, think of when you send someone an email.  When you send the email to them, your email address is included in the email.  Then, when they have read the email, (at their convenience) they reply and use the email address to send an email message back to you.

 

Another example, think of the Button.Click event (which we’ll see an example of later).  When the button is clicked, something needs to tell the compiler what “call back” method is supposed to be called (e.g. the “Button1_Click” Sub Procedure): That something is a Delegate.

 

So here’s an example where the “List(Of Type)” class is inherited by the “MyList(Of T)” class.  We will add a Delegate to the class to provide call back event notification when a new item is added to the list:

 

'Create a New List Class that Inherits the
'  List(Of T) class (The "T" stands for the
'  Type to be specified when the list is
'  declared)
Public Class MyList(Of T)
        Inherits List(Of T)

    'Create a "Call Back" Delegate to provide
    '  feedback when an item has been aded to
    '  the list
    Public Delegate Sub _
        ItemAddedDelegate(ByVal msg As String)


    'Create a private, internal variable that
    '  will store a reference to the
    '  "Call Back" ItemAddedDelegate
    Private AddedDelegate As ItemAddedDelegate


    'This method is used by the Caller to set
    '  the "Call Back" Delegate that will be
    '  Invoked when a new item is added to the
    '  list
    Public Sub OnItemAdded( _
            ByVal method As ItemAddedDelegate)

        'Set the "Call Back" delegate with the
        '  delegate passed in
        AddedDelegate = method

    End Sub


    'This is the method being called to add
    '  items to the list
    Public Shadows Sub Add(ByVal item As T)

        'Check to see if the item is already
        '  in the list
        If Me.Contains(item) Then

            'It's in the list, so invoke the
            '  "Call Back" Delegate and pass
            '  the response
            AddedDelegate(item.ToString() & _
                " not added, because it's" & _
                " already in the list")

        Else

            'It's not in the list, so add the
            '  item to the base class list
            '  (this prevents a recursive call
            '  the this Add method)
            MyBase.Add(item)

            '  Then invoke the "Call Back"
            '  Delegate and pass the response.
            AddedDelegate(item.ToString() & _
                " added to list")

        End If

    End Sub

End
Class

 

So, having looked at all of that, let’s see how it works from the caller’s end:

 

Public Class Form1

    'This is the "call back" method that gets
    '  called when the button is clicked.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click


        'Create a new instance of our list
        '  and set the Type (T) to Integer
        Dim list As New MyList(Of Integer)

        'Use "AddressOf" to create a new delegate
        '  that points to the "OnItemAdded" method.
        list.OnItemAdded(AddressOf OnItemAdded)

        'Add items to the list
        list.Add(1)
        list.Add(2)
        list.Add(3)
        list.Add(3)

    End Sub


    'This is the "Call Back" method that is being
    '  called when the delegate is invoked.
    Private Sub OnItemAdded(ByVal msg As String)

        'Print the response to the Output Window
        Console.WriteLine(msg)

    End Sub

End
Class

 

Hopefully that’s easy to understand!  If it doesn’t make since, then create a new Windows Forms project, add a Button to Form1, then go to the Form1 code window, highlight all of the code and delete it.  Then, copy the code for the Form1 class from the example above and paste it into the code window.  Finally, copy the code from the “MyList(Of T)” class and paste it after the Form1’s “End Class” keywords.  Run the project and click the button to see the results.  If you can set a breakpoint on the “list.Add(1)” line of code, then click the button, program execution will be halted at that line, then you can “step-into” (F11 in VS 10) the method and see how the delegate works.

 

And if you made it through that example ok, then you’re ready for some more advanced examples…

 

 

Examples of using Delegates in .NET

 

There are many classes in the .NET framework that use Delegates.  However, it may not always be obvious that a Delegate is being used. 

 

One plain give-away that a delegate is being used is that the “AddressOf” keyword is used.  When used in a Delegate constructor, the “AddressOf” operator assigns the specified method address to the Delegate.  When the “AddressOf” statement is used in context, the type of the delegate is determined by the compiler, and an instance of a delegate is created for you.

 

Having said that, let’s take a look at the generic List(Of Type) class that is located in System.Collections.Generic namespace.  There are 2 methods that we can look at:  The Sort method, which takes a System.Comparison(Of Type) delegate; and the Find method, which takes a System.Predicate(Of Type) delegate.

 

Because the List(Of Type) is a generic list, it literally can hold anything, once the Type has been specified.  For example, a List(Of String) can store a list of strings, a List(Of Integer) can store a list of integers, a List(Of TextBox) can store a list of TextBoxes, a List(Of Form) can store a list of Forms, and so on.  Because the list can store any type, the list wouldn’t have the ability to sort the items in the list, or search for items in the list, because it wouldn’t know how.  Therefore, methods such as the Sort and Find method must be programmatically defined.  And that’s where delegates come in!

 

Here’s a Sorting Delegate Example:

 

'Create a new list of Integers
Dim list As New List(Of Integer)

'Add 10 numbers to the list in reverse order
'  (10, 9, 8...)
For i As Integer = 10 To 1 Step -1
    list.Add(i) : Next


'Create a System.Comparison delegate
Dim sortListDelegate As  _
            System.Comparison(Of Integer)

'Use "AddressOf" to create the delegate and
'  assign the address of the SortList method

sortListDelegate = AddressOf SortList

'Call the Sort method of the list and pass
'  the sortListDelegate to it.  The "SortList"
'  Function will be used to sort the
'  Integers in the list.

list.Sort(sortListDelegate)

'Now that the list is sorted, print the
'  contents of the list to the Output Window
'  for verification
For i As Integer = 0 To list.Count - 1
    Console.WriteLine(list(i)) : Next

 

Here’s the “SortList” method being called by the “sortListDelegate” delegate:

 

'This method is being used to sort the list.
Private Function SortList(ByVal x As Integer, _
    ByVal y As Integer) As Integer

    Return x.CompareTo(y)

End Function

 

 

Here’s a Find Delegate Example:

 

'Create a new list of Integers
Dim list As New List(Of Integer)

'Add 10 numbers to the list
For i As Integer = 1 To 10
    list.Add(i) : Next


'Create a System.Predicate(Of Type) delegate
Dim findDelegate As System.Predicate(Of Integer)

'Use "AddressOf" to create the delegate and
'  assign the address of the FindInList method.

findDelegate = AddressOf FindInList

'Call the Find method of the list and pass
'  the findDelegate to it.  The "FindInList"
'  Function will be used to search the list.
Dim index As Integer = _
    list.Find(findDelegate)

'Print to Output Window
Console.WriteLine(list(index - 1))

 

And here’s the “FindInList” method that is being called by the “findDelegate”:

 

'This method is being used to search the list
Private Function FindInList(ByVal x As Integer) _
    As Boolean

    'Search the list for the number 5
    Return x = 5

End Function

 

 

As mentioned previously, every Event uses a Delegate.  An event that you are very familiar with is the Button.Click event.  This event too uses a Delegate.  Here’s an example, notice the use of “AddressOf” to create the Delegate:

 

'Create a new Button
Dim btn As New Button()

'Use "AddressOf" to create a delegate and
'  assign the address of the "Button_Click"
'  method to it.  .Net Creates an EventHandler
'  based off of the delegate.
AddHandler btn.Click, AddressOf Button_Click

'Click the button.  Under the hood the delegate
'  is invoked.

btn.PerformClick()

 

Here’s the Button_Click method that is being invoked by the delegate:

 

Private Sub Button_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs)

    MessageBox.Show("The button was clicked!")

End Sub

 

 

Multicasting Delegates

 

Up to this point we’ve learned that a Delegate has the ability to “point to” a method.  When the Delegate is invoked, the method that it “points to” is called.  Something we haven’t really discussed is the fact that a Delegate can actually “point to” more than one method at a time, and when it is invoked, all of the methods that it “points to” are called.  This is called “multicasting”.

 

As we’ve already seen, a Delegate must have the same signature (“shape”) as the method that it is point to.  This rule stays exactly the same when a Delegate “points to” multiple methods:  the Delegate has the have the same signature as every method that it points to.

 

In order to enable a Delegate to “point to” multiple methods, the System.Delegate.Combine method must be called.  The Combine method creates a new Delegate with an invocation list that concatenates the invocation lists of the delegates that are added, in the same order that they were added.

 

Here’s an initial example that demonstrates Delegate Multicasting:

 

'Create a Delegate for displaying a message.
Private Delegate Sub _
        MessageDelegate(ByVal msg As String)


Private Sub Button1_Click( _
    ByVal sender As Object, _
    ByVal e As System.EventArgs) _
    Handles Button2.Click

    'Create 3 instances of the MessageDelegate
    '  that point to different methods
    Dim d1 As MessageDelegate = _
                    AddressOf DisplayMessage1
    Dim d2 As MessageDelegate = _
                    AddressOf DisplayMessage2
    Dim d3 As MessageDelegate = _
                    AddressOf DisplayMessage3


    'Delegates will be concatenated in the same
    '  order that they are added to the list
    '  which in this case is "d1", "d2", "d3"
    Dim d As MessageDelegate = _
        System.Delegate.Combine(d1, d2, d3)


    'Invoking this delegate actually invokes
    '  all 3 delegates in the same order they
    '  were added.
    d("Hello World of Delegate Multicasting!")


End Sub


'This method will be called by "d1" delegate
Private Sub DisplayMessage1(ByVal msg As String)

    Console.WriteLine("DisplayMessage1:  " & msg)

End Sub


'This method will be called by "d2" delegate
Private Sub DisplayMessage2(ByVal msg As String)

    Console.WriteLine("DisplayMessage2:  " & msg)

End Sub


'This method will be called by "d3" delegate
Private Sub DisplayMessage3(ByVal msg As String)

    Console.WriteLine("DisplayMessage3:  " & msg)

End Sub

 

Notice that the “d1”, “d2” and “d3” delegates all pointed to methods with the same exact signature (ByVal msg As String):  DisplayMessage1, DisplayMessage2, DisplayMessage3.

 

The Output from the above example looks like this:

 

multicasting

 

 

A more sophisticated example could expand upon the “Event Handling with Delegates” example above, and change the way the “MyList(Of T)” class sets the “call back” delegate in the “OnItemAdded” method.  Also, we can add an “OnItemRemoved” method that can be used by the caller to set a “call back” delegate that can be invoked when an item has been removed from the list.

 

By enabling multicasting in the “OnItemAdded” delegate event, and in a new “OnItemRemoved” delegate event, we allow the caller to set multiple call back delegates that can be invoked.  Then the caller can create different methods to respond when items are added, removed, and when the list changes. 

 

Quite a few things have changed in this example, so if you saw the previous example in the “Event Handling with Delegates” section, make sure you take the time to notice the differences.

 

Here’s the example:

 

'Create a New List Class that Inherits the
'  List(Of T) class (The "T" stands for the
'  Type to be specified when the list is
'  declared)
Public Class MyList(Of T)
        Inherits List(Of T)

    'Create a "Call Back" Delegate to provide
    '  feedback when this list has changed
    Public Delegate Sub _
        ListChangedDelegate(ByVal msg As String)



    'Create a private, internal variable that
    '  will store a reference to the
    '  "Call Back" ListChangedDelegate
    '  that will be invoked when an item has
    '  been added to the list.
    Private AddedDelegate As ListChangedDelegate


    'This method is used by the Caller to set
    '  the "Call Back" Delegate that will be
    '  Invoked when a new item is added to the
    '  list
    Public Sub OnItemAdded( _
            ByVal method As ListChangedDelegate)

        'Multicasting:
        'Set the "Call Back" delegate with the
        '  delegate passed in
        AddedDelegate = _
            System.Delegate.Combine(AddedDelegate, _
                                    method)

    End Sub


    'This is the method being called to add
    '  items to the list
    Public Shadows Sub Add(ByVal item As T)

        'Check to see if the item is already
        '  in the list
        If Me.Contains(item) Then

            'It's in the list, so invoke the
            '  "Call Back" Delegate and pass
            '  the response
            AddedDelegate(item.ToString() & _
                " not added, because it's" & _
                " already in the list")

        Else

            'It's not in the list, so add the
            '  item to the base class list
            '  (this prevents a recursive call
            '  the this Add method)
            MyBase.Add(item)

            'Then invoke the "Call Back"
            '  Delegate and pass the response.
            AddedDelegate(item.ToString() & _
                " added to list")

        End If

    End Sub



    'Create a private, internal variable that
    '  will store a reference to the
    '  "Call Back" ListChangedDelegate
    '  that will be invoked when an item has
    '  been removed from the list.
    Private RemovedDelegate As ListChangedDelegate


    'This method is used by the Caller to set
    '  the "Call Back" Delegate that will be
    '  Invoked when an item is removed from
    '  the list
    Public Sub OnItemRemoved( _
            ByVal method As ListChangedDelegate)

        'Multicasting:
        'Set the "Call Back" delegate with the
        '  delegate passed in
        RemovedDelegate = _
            System.Delegate.Combine(RemovedDelegate, _
                                    method)

    End Sub


    'This is the method being called to remove
    '  items from the list
    Public Shadows Function Remove( _
                    ByVal item As T) As Boolean

        'Check to see if the item is in
        '  the list
        If Me.Contains(item) Then

            'It's in the list, so remove
            '  the item from the base class
            '  list.
            MyBase.Remove(item)

            'Then invoke the "Call Back"
            '  Delegate and pass the response.
            RemovedDelegate(item.ToString() & _
                " removed from list")

            Return True

        Else

            'It's not in the list, so invoke  
            '  the "Call Back" Delegate and
            '  pass the response
            RemovedDelegate(item.ToString() & _
                " not removed, because it's" & _
                " not in the list.")

            Return False

        End If

    End Function

End
Class

 

Ok, so now that we have our multicast enabled “MyList(Of T)” class, let’s take a look at how to use it:

 

Public Class Form1

    'This is the "call back" method that
    '  gets called when the button is clicked.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click


        'Create a new instance of our list
        '  and set the Type (T) to Integer
        Dim list As New MyList(Of Integer)

        'Multicasting of AddedDelegate
        list.OnItemAdded(AddressOf _
                            OnItemAdded)
        list.OnItemAdded(AddressOf _
                            OnListChanged)

        'Multicasting of RemovedDelegate
        list.OnItemRemoved(AddressOf _
                            OnItemRemoved)
        list.OnItemRemoved(AddressOf _
                            OnListChanged)

        'Add items to the list
        list.Add(1)
        list.Add(2)
        list.Add(3)
        list.Add(3)

        'Remove items from the list
        list.Remove(1)
        list.Remove(3)
        list.Remove(3)

    End Sub


    'This is the "Call Back" method that is being
    '  called when the AddedDelegate delegate is
    '  invoked.
    Private Sub OnItemAdded(ByVal msg As String)

        'Print the response to the Output Window
        Console.WriteLine("OnItemAdded:    " & msg)

    End Sub


    'This is the "Call Back" method that is being
    '  called when the AddedDelegate delegate or
    '  RemovedDelegate delegate is invoked
    Private Sub OnListChanged(ByVal msg As String)

        Console.WriteLine("OnListChanged:  " & msg)

    End Sub


    'This is the "Call Back" method that is being
    '  called when the RemovedDelegate delegate is
    '  invoked
    Private Sub OnItemRemoved(ByVal msg As String)

        Console.WriteLine("OnItemRemoved:  " & msg)

    End Sub

End
Class

 

 

Summary

So we learned that Delegates are basically pointers to methods that can be invoked at any time.  We also learned that Delegates are strongly-typed, and must have a signature that identically matches the signature of the method that they point to.  We also learned that a Delegate intrinsically support multicasting, so that a Delegate can point to multiple methods, not just one method.

 

If you have a pretty solid understanding of Delegates, then you’re ready to dive into Events, which you’re going to love, because they are designed to lessen the burden of using Delegates in the raw. 

0 comments:

Leave a Reply

Translate

Google-Translate-Chinese (Simplified) BETA Google-Translate-English to French Google-Translate-English to German Google-Translate-English to Italian Google-Translate-English to Japanese BETA Google-Translate-English to Korean BETA Google-Translate-English to Russian BETA Google-Translate-English to Spanish

Tags