On Fri, 25 Apr 2008 08:09:18 -0700, Cowboy (Gregory A. Beamer)
<No************ @comcast.netNoS pamMwrote:
Ignacio points out the primary reason: You are not sure what you are
calling
until runtime.
Careful with the "until runtime". _Some_ code usually knows what's going
to be called at compile time. It's just that the _calling_ code doesn't
know until runtime.
With that in mind, I'd say that technically speaking, all uses of
delegates fall into this category. For example...
Delegates are aslo useful for event handlers, when you only want a
specific
bit of code called in a certain instance.
But the reason they are used for event handlers is that at compile time,
the implementer of the event doesn't know what code will be called. The
..NET Forms classes are a classic example of this. Microsoft can't
possibly know what your own code would be when they provide an event. So
using a delegate allows other code to provide the reference to the method
to be called, well after the point at which Microsoft's code was compiled.
Another reason to delegate is callbacks, which cannot be coded directly
as
method calls.
That's not strictly speaking correct, depending on what you mean by "as
method calls". Java doesn't have any idea like delegates, and yet it can
implement the same sort of behavior. It uses interfaces instead. And
those are coded directly as method calls (i.e. a method defined in an
interface implemented by whichever class wants to provide the callback).
This could be done in .NET, and in fact for more elaborate APIs is in fact
used quite a lot.
But regardless, that's still a subset of the general "you don't know at
compile time the exact method that will be called".
I prefer delegates, and I feel that for single-method situations they are
way more convenient than having to create a whole interface and then
implement it in each class that wants to provide a method to call at
specific times (whether to support events, i/o callbacks, whatever). But
you don't _have_ to have delegates to allow for callbacks that aren't
known at compile time.
Pete