Events & Delegates: Using Delegates with event

One of the basic issues for programming beginners is the concept of “Events & Delegates” . Generally all of us, including me, work on event driven programs. People often find it difficult to see the difference between events and delegates. I hope this article will prove to be a big help for all those who want to understand what are events and delegates and how one can handle an event.

Delegates

A Delegate is a functional variable that contains a reference to a method rather than the method name. Using Delegates, Method to be called at runtime can be identified. A delegate also means Instantiating a method using delegates. A method can also be called without knowing its name. After running a delegate, it will execute the method that it references. A delegate is more like having a general method name, pointing this name to various methods in different times, and executing those methods through the delegate.

Declare Delegates

Firstly, I create a delegate with “delegate” keyword, followed by a return type of method, as shown below: delegatesEvents

An Event is either activated by the user like on mouse click or a press key. When an event is triggered it requests a program to be executed for instance, if I want to send an email I will click on send button, as soon as I click on send button it generates an event through which it sends email over the internet. When an event occurs, the application should be able to respond to it or manage it. Events are raised at the client machine and it is handled at server machine. This handling of an event is called an Event Handler.

Declare Event

Before declaring an event, I should create a delegate. Because, delegate defines type of an event. So, if you want to declare an event, you just declare the type of variable (event) through delegates. As follows: event Events and Delegates work with each other to provide a program’s functionality. It starts with a class that declares an event. Events use the publisher-subscriber model. The class that contains event is called publisher class and is used to publish the event. The event-delegate association is also defined in this object. And the other class is known as the subscriber class which accepts the event. The delegate in the publisher class invokes the method or event handler of the subscriber class. Let’s create a simple program of event and delegates in C#:

prog I hope that this article may help you to understand the concept of Events & Delegates easily. These small concepts serve as the building blocks for an ideal program. An ideal program must be one that can be understood by the reader and must not look like a mess. Now you must apply this in your programs to make them more efficient and coherent.

Your email address will not be published. Required fields are marked *

Contact CPD Technologies






    [recaptcha]