OpticTygre wrote:
Ok, so I've been trying and trying to learn about delegates, but I
still can't grasp the concept of the advantages. Why use delegate
functions instead of calling the function directly?
In other words, if I had something like:
---------------------------------------------
Public Class ProductList
Public Function GetTotal() as Decimal
'Code omitted
End Function
End Class
---------------------------------------------
And then something like:
---------------------------------------------
Public Delegate Function GetTotalDelegate() as Decimal
Dim List As New ProductList()
Dim GetTotalPointer As New GetTotalDelegate(AddressOf List.GetTotal)
Dim Total As Decimal
Total = GetTotalPointer()
---------------------------------------------
Why use a delegate call instead of just saying Total =
ProductList.GetTotal() ?????
Thanks for any explanations
Indeed in this example there is no reason for the use of a delegate.
Delegates come in useful in more generic situations, where you *don't
know* what you are calling. If you like, you can consider a Delegate
type as an ultra-small Interface that consists of a single call. Like
an Interface, a Delegate type defines a *contract of behaviour*.
The usual place Delegates are found is in event handling. Suppose I
create a Phone class that raises an IncomingCall event. I want clients
of mine to be able to react to that event, so there needs to be some
defined mechanism by which clients can attach themselves to me.
What happens is that I define a Delegate type for that event: In
effect, I say to potential clients, "If you want to consume the
IncomingCall event, you must provide me with a function that accepts an
IncomingCallEventArgs and returns an Integer". That function signature
in effect *is* the Delegate type.
When clients pass me functions that match that signature, I have no
idea what those functions are, except that they match the signature.
They could be global module functions, shared class functions, class
instance methods - anything. All I *need* to know is that they accept
an IncomingCallEventArgs, and return me an Integer.
Thus we see that as with the concept of an Interface, the Delegate
provides a way to *encapsulate* behaviour and create *loosely-coupled*
components. *Contract-based programming* is another key phrase to throw
in there :)
--
Larry Lard
Replies to group please