Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The purpose of delegates [duplicate]

Tags:

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?

like image 852
KdgDev Avatar asked Mar 26 '09 21:03

KdgDev


People also ask

What is the purpose of delegates?

Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

Why delegate is faster?

Delegates are faster because they are only a pointer to a method. Interfaces need to use a v-table to then find a delegate; They are equal, but delegates are easier to use.


1 Answers

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...

like image 110
Ian Avatar answered Sep 27 '22 20:09

Ian