tags:

views:

959

answers:

8

Duplicate:

Difference between events and delegates and its respective applications

What are the advantages of delegates?

Where do I use delegates?

I wonder what the purpose of delegates is. I haven't used them that much and can't really think of something.

In my courses, it's written that a delegate is a blue-print for all methods that comply with its signature.

Also, you can add multiple methods to one delegate, and then they'll be executed after eachother in the order they were added. Which is probably only usefull for methods that affect local variables or methodes that don't return any values.

I've read that C# implements Events as delegates, which is documented as being:

//Summary: Represents the method that
will handle an event that has no event
data.

//Parameters:

//sender: The source of the event.

//e: An System.EventArgs that contains no event data.

[Serializable]

[ComVisible(true)] 

public delegate void EventHandler(object sender, EventArgs e);

Still, it's kinda confusing. Can someone give a good, usefull example of this concept?

+1  A: 

I can provide you with an example using a web application architecture:

Generally, with a web application you can provide a front controller that receives requests from many clients. We could put all our methods within the front controller for dealing with the many different types of requests from the clients. However, this get a little cumbersome. Instead we can use delegates to encapsulate functionality for different requests. We could have:

  • Authentication Delegate
  • User Management Delegate

and so on. So it's a neat way to split up functionality into logical chunks - delegates. The Struts framework is based on this way of working (the ActionServlet and Action classes).

Jon
+8  A: 

Yeah,

You're almost there. A delegate refers to a method or function to be called. .NET uses the Events to say.. when someones presses this button, I want you to execute this piece of code.

For example, in the use of a GPS application:

public delegate void PositionReceivedEventHandler(double latitude, double longitude);

This says that the method must take two doubles as the inputs, and return void. When we come to defining an event:

public event PositionReceivedEventHandler PositionReceived;

This means that the PositionRecieved event, calls a method with the same definition as the PositionReceivedEventHandler delegate we defined. So when you do

PositionRecieved += new PositionReceivedEventHandler(method_Name);

The method_Name must match the delegate, so that we know how to execute the method, what parameters it's expecting. If you use a Visual Studio designer to add some events to a button for example, it will all work on a delegate expecting an object and an EventArgs parameter.

Hope that helps some...

Ian
A: 

This question is quite similar to several other questions on SO. (I'm not voting to close because it's not quite identical and I think some more explanations may be worthwhile.) See these in particular:

Noldorin
If it's a duplicate, post it in the comments or edit the post showing the dupes. Don't just power an answer with dupe questions to garner cheap rep.
TheTXI
wah wah wah. If it's a useful answer, it'll get the rep it deserves. If not, it'll get the rep it deserves.
Adam Davis
@TheTXI: I didn't consider this the most clear-cut case, so deciding *not* to vote to close, I thought posting this as an answer would be fair. Also, there's are plenty of other questions with similar answers (containing links to duplicates), so why shouldn't I do the same?
Noldorin
I never said myself anything about voting to close, but I don't see why posting the dupes in the comments or including them in the original topic would have been out of the question. Oh well. It's not like I could vote you up or down anyway since I am out of votes for the day.
TheTXI
My point was that it may have been hypocritical to answer and then vote to close, hence I did not. And you may not have down-voted me, but your comment does seem to have encouraged others... Thanks very much.
Noldorin
This is not the point of an answer. The point of an answer is to ... y'know, answer the question, not bitch about dupes. The place for that is the comments of the question.
belgariontheking
I don't consider linking to duplicates any different than linking to external sites... I'm indirectly providing an answer either way.
Noldorin
@Noldorin: No you're not.
belgariontheking
Noldorin - most of us are against links to other sites without some real answer material as well. Links are limited - if the site goes away, or they re-factor their links, etc then the info is lost. Always try to include the meaty part of the answer in the answer.
Adam Davis
@New Improved BTK: Oh, I do enjoy being told what to do by a newbie.@Adam Davis: Point taken regarding broken links. (I tend to link mainly because other people have clearly gone to a good deal effort creating an answer, but copying with a brief explanation may be be better for the long-term.)
Noldorin
+1  A: 

There are lots of excellent articles explaining delegates - here are some good ones:

Delegates and events
C# Delegates Explained
Delegates in C#

Andrew Hare
This answer really doesn't deserve down-votes either. Hrmm...
Noldorin
+4  A: 

As you noted a delegate is a way to create a signature for an method call. There are many great examples of using delegates, but the one that really opened my mind is this example.

public delegate Duck GetDuckDelegate();

public GetDuckDelegate GiveMeTheDuckFactoryMethod(string type)
{
  switch(type)
  {
    case "Rubber":
      return new GetDuckDelegate(CreateRubberDuck);
    case "Mallard":
      return new GetDuckDelegate(CreateMallardDuck);
    default:
      return new GetDuckDelegate(CreateDefaultDuck);
  }
}

public Duck CreateRubberDuck()
{
  return new RubberDuck();
}

public Duck CreateMallardDuck()
{
  return new MallardDuck();
}

public Duck CreateDefaultDuck()
{
  return new Duck();
}

Then to use it

public static void Main() {
  var getDuck = GiveMeTheDuckFactoryMethod("Rubber");
  var duck = getDuck();
}

Arguably, the Factory pattern would be a better method for this, but I just thought up this example on the fly and thought it proved the point of how delegates can be treated as objects

bendewey
A very nice example. Thanks.
WebDevHobo
+1  A: 

Delegates allow you to pass methods around like values.

For example, .Net has a method called Array.ForEach that takes a delegate and an array, and calls the delegate on each element of the array.

Therefore, you could write,

int[] arr = new int[] { 1, 2, 4, 8, 16, 32, 64 };
Array.ForEach(arr, new Action<int>(Console.WriteLine));

This code will call Console.WriteLine for each number in the array.

There are many things you can do by making functions that take delegates, especially when combined with anonymous methods. For examples, look at LINQ.

SLaks
i believe you are missing a ) on your ForEach
bendewey
Fixed; thanks.
SLaks
+1  A: 

Delegates, to my understanding, provides a way of specializing the behavior of a class without subclassing it.

Some classes have complex generic behavior, but are still meant to be specialized. Think of a Window class in a GUI framework: A Window can propably do a lot on it's own, but you would most likely still want to specialize it in some way. In some frameworks, this is done via inheritance. A different way of doing it is with delegates. Say you want something to happen when the Window resizes: Your delegate class can then implement a method called onWindowResize (provided of course that the Window class supports this), which gets called whenever the Window resizes and is responsible for any specialized behavior when the Window resizes.

I'm not going to argue the merits of delegation over inheritance, but suffice it to say that there are many who feel that delegation is "cleaner" than inheritance.

KaptajnKold
A: 

Many people initially get confused with the real need for delegates and events. I was one of them and it took me some time to figure it out :-). Recently answered a similar query in ASP.NET forums and thought it would be good if I create a blog post on this topic! Here was the query:

"I was reading an example somewhere of a Bank Class that if the minimum balance is reached you need to inform the rest of the app that the min has reached, but can't we do that by just calling a normal method. for example: lets say when we deduct some amount from the balance and if minimum reached then call some method to take some action, I am totally missing why do we need delegates and custom events here?"

Thing is in the Bank case, you can definitely call a method, but then it would be simple procedural programming, we need event based programming when we want our code to respond to some events generated by a system.

For eg.: think that windows OS is a system, and we are writing a code (in any language) where we want to capture an event like mouse_click(). Now how would our program know that a mouse click has occured? We can use low level code for it, but since OS is already handling low level code, its best to capture an event raised by the OS.

In other terms, the moment a mouse_click() happens the OS fires an event. The OS doesnt care who captures this event and uses it, it just sends out a notification. Then any code (like ours) can capture that event and use it accordingly. This saves us a lot of time to write code for the same ourselves. And other programs too can use the same event and handle it accordingly.

Similarly, the banking system can be huge, and many other outside applications might be accessing it. The banking system does not know how many such applications there are which need it, or are dependent on it, and how would they handle certain situations like when balance is low, so it simply fires an event whenever low balance occurs, and this event can be used by any other code, besides banking code itself.

Note that each susbcriber to that event can handle that event independently, for eg. the banking code might stop something from executing if balance is low, some other reporting app might send an email in such a case, or some ATM code can stop a particualr transaction and notify the user that balance is low.

Hope this clears things a bit!