The purpose of delegates [duplicate]

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…

Leave a Comment