Let me explain.
When you define a type Integer you say that you will need at least 4 bytes to store its value. By itself Integer is just a type - you cannot store actual values in it.
But when you declare a variable:
- you say that you need a place in your app's memory heap to store the values for this variable.
the same with delegates
You declare that there is somewhere a method that accepts two integers and returns a string.
So you declare a delegate:
vb.net Code:
Delegate Function MyDelegate(ByVal Arg1 As Integer, ByVal Arg2 As Integer) As String
The part (ByVal Arg1 As Integer, ByVal Arg2 As Integer) As String is called a method's signature and it says that when you need to invoke something using this delegate you will have to provide exactly two integers and expect a string for return value.
So now, I'm designing some class that uses a callback procedure. The user has to know what is the signature for that callback, so you declare the member like this:
vb.net Code:
Private Function MyWork(ByVal id As MyDelegate) As String
' I do not know what will be done with these two integers, I simply invoke
' the delegate provided, get the return value and return it back
Dim PassedInt1 As Integer = 1
Dim PassedInt2 As Integer = 2
Dim ret As String = id.Invoke(PassedInt1, PassedInt2)
Return ret
End Function
This can be helpful if you are working with third party components and you will have to redefine the behaviour of the algorithm from time to time.
Of course we need a callback procedure that will be invoked by the MyWork, note that its 'signature' corresponds with the delegate signature:
vb.net Code:
Private Function MyCallBack1(ByVal i1 As Integer, ByVal i2 As Integer) As String
Return (i1 + i2).ToString
End Function
But what if we wanted to redefine the way our integers will be processed? Well, we provide another callback procedure for that. Note again that our second callback procedure has the identical 'signature':
vb.net Code:
Private Function MyCallBack2(ByVal i1 As Integer, ByVal i2 As Integer) As String
' I can redefine the callback procedure
Return (i1 * i2).ToString
End Function
I call the MyWork function (it can be done even from a remote machine) and provide it with two pointers of the type MyDelegate:
vb.net Code:
Private Sub DoMyWork()
MsgBox(MyWork(AddressOf MyCallBack1))
MsgBox(MyWork(AddressOf MyCallBack2))
End Sub
Hope this helps. Sometimes using delegates is the only way out when you're in a multithreaded or distributed environment.