Why use Delegates?

S

samadams_2006

Hello,

I'm trying to figure out why delegates are such a great thing. For
example, I came across the following line of code:

"This ability to refer to a method as a parameter makes delegates
ideal for defining callback methods. For example, a sort algorithm
could be passed a reference to the method that compares two objects.
Separating the comparison code allows the algorithm to be written in a
more general way."

Can someone explain this to me?

Thanks
Sam
 
S

sloan

The quote you provide, look here:
http://www.dofactory.com/Patterns/PatternStrategy.aspx

Event and delegates are kinda DotNet's "built in" observer pattern.
Check this:
http://www.dofactory.com/Patterns/PatternObserver.aspx

This would be the most obvious to me.

When something "happens"....you can register and unregister things which are
interested in it.

Let's say you write software for your state school system.

When a new student is registered...today, maybe the school and the county
and the state are interested.
However, tomorrow, the cdc might be interested in it.
You code it up to "raise events" when a student is added, and thus you can
add/remove people who are interested in it.

Its a way to build maintainable code at its heart.

I would recommend the "Head First Design Pattern" book if you're serious
about software development for the long haul.
 
S

samadams_2006

Maybe I'm not seeing it... Let's look at the example in the first
link provided above. Here it is:

class MainApp
{
static void Main()
{
// Two contexts following different strategies
SortedList studentRecords = new SortedList();

studentRecords.Add("Samual");
studentRecords.Add("Jimmy");
studentRecords.Add("Sandra");
studentRecords.Add("Vivek");
studentRecords.Add("Anna");

studentRecords.SetSortStrategy(new QuickSort());
studentRecords.Sort();

studentRecords.SetSortStrategy(new ShellSort());
studentRecords.Sort();

studentRecords.SetSortStrategy(new MergeSort());
studentRecords.Sort();

// Wait for user
Console.Read();
}
}

Why couldn't you just define 3 new methods, as shown below, and get
rid of the "SetSortStrategy":

studentRecords.QuickSort();
studentRecords.Sort();

studentRecords.ShellSort();
studentRecords.Sort();

studentRecords.MergeSort();
studentRecords.Sort();

If you wanted to add another algorithm, such as: BubbleSort(), you
would still need to add this algorithms to the code, and compile it.
I've heard that one of the features of delegates is that it is is more
"dynamic"....doesn't seem to dynamic to me?

Thanks
 
G

Gregory A. Beamer \(Cowboy\) - MVP

It is not a traditional delegate, as in setting up the delegate using the
keyword delegate, but the activity is being delegated off to the method. The
syntax for the strategy, in many ways, can be accomplished using a declared
delegate (as in an anonymous method), ala
http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx

Now my brain is going. Add some generics and ... Okay, I am probably going
to confuse the OP, so I am shutting up now. ;-)

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#

or just read it:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think outside the box! |
********************************************
Peter Duniho said:
Maybe I'm not seeing it... Let's look at the example in the first
link provided above. Here it is: [...]

Okay, so first let's make something clear: that code doesn't use
delegates. It uses an abstract class, and in fact it uses the abstract
class as an interface (suggesting that it should in fact have been an
interface, but we'll leave that criticism of the example aside for now
) ).

Now, the interface -- I mean, abstract class :) -- does happen to be a
single-method class, and in that respect is very similar to a delegate (in
the same way a delegate is similar to a single-method interface, as I
mentioned before). But you should be clear that the only reason that link
is pertinent here is that it discusses a particular _design_ pattern that
could be implemented using delegates. In that particular example, the
actual implementation uses an abstract class instead.

Now, that said...if we treat the abstract class sub-class as a delegate,
we can in fact make some useful observations about the code sample. So,
let's do that... :)
[...]
Why couldn't you just define 3 new methods, as shown below, and get
rid of the "SetSortStrategy":

studentRecords.QuickSort();
studentRecords.Sort();

studentRecords.ShellSort();
studentRecords.Sort();

studentRecords.MergeSort();
studentRecords.Sort();

First point: if the "QuickSort()" method actually sorts the list, then
calling "Sort()" again after doesn't make sense. So let's assume that in
your modification, you intend for the "QuickSort()" method to simply set
the sort strategy rather than sorting the list.

With that in mind, if you wrote the code as you've modified it the
SortedList class would need to anticipate all possible sort strategies and
provide specific methods for each one. Using an abstract class as shown
on the web site (or an interface or a delegate as is also possible) the
SortedList doesn't need to know _anything_ about the specific sorting
technique. It just needs to know that when the client of the SortedList
class wants to order the list, it will provide a method that takes a
single ArrayList as an argument and returns void.

An abstract class, an interface, and a delegate all provide different
mechanisms for this kind of declaration.

If and when the SortedList class then wants to sort itself, it will simply
call that provided implementation to do the work. Again, it never has to
know _how_ that work is implemented. It just declares the method
signature that it will require for doing the work, and it delegates the
work to code implemented elsewhere (and quite possibly at some much later
time).

In fact, it's from this delegation that the word "delegate" comes from.
If you wanted to add another algorithm, such as: BubbleSort(), you
would still need to add this algorithms to the code, and compile it.
I've heard that one of the features of delegates is that it is is more
"dynamic"....doesn't seem to dynamic to me?

It seems very dynamic to me. Note in on that web page that each
implementation of the sorting strategy is a completely different class,
and that the SortedList class doesn't need to anything about those
specific implementations. It knows the abstract base class, and nothing
else.

This means that anyone can use the SortedList class, providing their own
SortStrategy implementation. That implementation can be defined anywhere,
at any time. The implementation can do _whatever_ it wants, and
SortedList never has to worry about the exact implementation.

Delegates work in very much the same way. Something can declare a
delegate type, using that type in its own code, without there being any
implementation of the delegate type at the time the using code is
written. The delegate implementation can be provided later, at the
convenience of whatever code uses the code specifying the delegate type.
As long as the implementation matches the signature specified by the
delegate type, code using the delegate type will compile. (There may be
additional specifications on the implementation, as is the case with
comparison delegates -- that is, a comparison delegate is required to
follow some basic consistency rules for sorting to work).

Pete
 
J

Jeff Louie

Sam... As you can gleam from the responses here: delegates, interfaces
and
inheritance can all be used to provide runtime variation in behavior.
What we are
really talking about here is different idioms used to achieve runtime
polymorphism.

Runtime polymorphism involves programming to a type, such that the
implementation details can be different and are discoverable at runtime.
When
programming to a type, the caller does not know the class of the object,
only
that the object implements the type of interest. Polymorphic behavior
can be
achieved using using interfaces, abstract classes/subclassing or
delegates/events. Each approach has advantages and disadvantages.

Regards,
Jeff
 
R

raylopez99

Hello,

I'm trying to figure out why delegates are such a great thing.  For
example, I came across the following line of code:

"This ability to refer to a method as a parameter makes delegates
ideal for defining callback methods. For example, a sort algorithm
could be passed a reference to the method that compares two objects.
Separating the comparison code allows the algorithm to be written in a
more general way."

Can someone explain this to me?

Thanks
Sam

I was like you about three months ago.

My newbie advice: get the book by Albahari C#3.0 in a nutshell. or,
just study delegates until your eyeballs drop out. Then study events
(a form of delegate). After about the tenth example it finally dawns
on you.

The way I like to think of it (and others on this board disagree):
delegates are a kind of global "GOTO" statement, where a function/
method can fire a delegate GOTO and have several portions of code that
are "registered" to listen to the delegate execute code the minute the
function/method fires, even when the function/method is unaware of
these registered portions of code. So you can have multiple "GOTO"s
execute simultaneously.

If that sounds complicated, it is. Believe me, delegates will make
your head hurt. But there's no other way to learn them. Nothing
anybody says in this thread--no matter how right--even me--will make
you understand delegates. You just have to keep trying until you
finally 'get it'.

Good luck.

RL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top