473,385 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Why use Delegates?

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
Oct 23 '08 #1
4 1778

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.


<sa***********@yahoo.cawrote in message
news:bf**********************************@k37g2000 hsf.googlegroups.com...
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

Oct 23 '08 #2

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

Oct 24 '08 #3
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

*** Sent via Developersdex http://www.developersdex.com ***
Oct 24 '08 #4
On Oct 23, 3:40*pm, samadams_2...@yahoo.ca wrote:
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
Oct 25 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Jeffrey T. Smith | last post by:
Back when the new J2SE1.5 features were announced, there was a JavaLive community chat (http://java.sun.com/developer/community/chat/JavaLive/2003/jl0729.html) in which Neal Gafter explains the...
3
by: Sam | last post by:
I’m just starting to learn delegates. I’m at the very beginning. If I understand correctly, delegates are for when you want to pass a function as a parameter. For example the client provides a...
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
4
by: AMDRIT | last post by:
I am trying to understand Delegates and where/when to use them. I can see one potential use of a delegate (on form closing, set the cancel property in the event arguments.) Does anyone have a...
6
by: =?Utf-8?B?Sko=?= | last post by:
I have a logger component that logs to multiple sources, ie textfile, eventlog etc. and I have two methods that depending on where I call up my logger comp. one of them will be called. For ex. if...
0
by: bharathreddy | last post by:
Delegates Here in this article I will explain about delegates in brief. Some important points about delegates. This article is meant to only those who already know delegates, it will be a quick...
6
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes...
7
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that...
69
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same...
9
by: raylopez99 | last post by:
Hello all— I’m trying to get the below to work and cannot get the format right. It’s from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: I’m trying...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.