jump to navigation

How to use .NET Delegates and event handling using delegates July 22, 2008

Posted by fofo in .NET, C#, c# 3.0.
Tags:
trackback

One of the issues that troubles most novice developers is the concept of “delegates”. In this post I will try through definitions and practical examples to explain delegates and what is the relation of delegates and events. If you come from a C/C++ environment you can think delegates as function pointers. Basically function pointers are variables that hold the memory address of a function. So when we invoke that variable, a call is made to the underlying function.

In the .Net world we can simply say that delegates are type-safe .NET objects (like everything else) which points to a method that matches its specific signature.Delegates derive from the System.Delegate class.

In order to see how delegates work we will review a simple example.I would like to point out that i am talking about single cast delegates. A single cast delegate can invoke a single method.

 1) Create a simple asp.net web application with C#

 2) Add a new item, a class file, and call it delegate (delegate.cs)

 3) In this class file add this public function

public int addnumbers(int myfirstnum, int mysecondnum)
    {
        int result;
        result = myfirstnum + mysecondnum;
        return result;
    } 

4) In the Page Load event of the default.aspx add the code below

delegateclass theDelegate = new delegateclass();
myDelegate delegateAddition = new myDelegate(theDelegate.addnumbers);

int addition = delegateAddition(10, 89);

Response.Write(“</br>”);

Response.Write(addition.ToString());

5) Place the code below which declares a delegate that takes two integer type as arguments and returns an integer as return type, just above your Page_Load event handler method

public delegate int myDelegate(int thefirst,int thesecond);

I will try to explain what the code does.

myDelegate delegateAddition = new myDelegate(theDelegate.addnumbers);

 I have created a delegate variable(delegateAddition) of type myDelegate. Using the delegate variable, I can point to any method that has the matching signature.

In the above example the method addnumbers has the same signature with the delegate variable. I use the new keyword to reference the delegate variable to the addnumbers method.

Then I call the function addnumbers by passing required parameters through the delegate.

int addition = delegateAddition(10, 89);

6) Run your application

In this second part of the post I would like to talk about delegates and events.

Some people do not understand why we need to use delegates in the event communication process.

Let’s imagine that we have a created/developed a multi-tier application for a supermarket. In our business logic layer we can have a class(productstock) that among other things checks the stock limit of any particular product. If the minimum of stock for any given product is reached this class should notify the other parts of the application. I can hear people saying, “Well, where is the problem? We do not need delagates. We simply call a normal method, that might call another method and so on…”

I think we can understand more about the scenario above if we see how events are raised and captured by applications.

We want to handle our events. That is why we write so much code in the event handlers like (e.g button_click). But how on earth knows our application that a button has been clicked?

Well the operating system, the moment the button_click happens, it fires an event.The operating system does not care who will capture this event. It just notifies everyone that “well guys out there, a button_click event has taken place”. Our code(event handling routine) can capture this event and do whaterver it must do.But any other programs can use this event now that they are notified.

In our productstock class, in our supermarket application, the application does not know what other applications need to know about the stock limit of a product running low. So it justs fires an event whenever stock is low for any product and notifies other application like, an application that sends an email to the manager of the supermarket informing him that stock is running low, an other application that may cancel or initiate another transaction.

Hopefully it is much clearer now.Let’s take the example above and explain it with .Net terms.

An event in the .NET Framework world enables objects of a class to notify other objects that an action has been performed and that they should react. The model on which the events in the .Net Framework are based is the publisher-subscriber model. The class that publishes the event is the publisher. The class that registers to the published event is the suscriber class.

In C#,VB any object can publish a set of events. Other applications can subscribe to these events. When the publishing class raises an event, all the subscribed applications are notified.But the publisher doesn’t know who is going to subscribe the event.  Delegates act as an intermediary between the publisher and the subscriber.

Let’s see another example

1) Create an ASP.Net web application with C#

2) We will create  a class that will publish the events. Add a new item to the project, a class file and call it Publisher.cs.

3) Add the code below inside the public class Publisher

  public event DelegateEvent theevent;
  public delegate void DelegateEvent(object from, EventArgs args);

  public void raiseEvent(EventArgs args)
  {
      theevent(this, args);
  }

   public Publisher()
   {
   

   }

public void SendTheEvent()
   {
         MessageBox.Show(“the event is fired here”);
         this.raiseEvent(new EventArgs());
   }

Let me explain what I do here.

First I declare the event

public event DelegateEvent theevent;

Use a delagate to publish our event

public delegate void DelegateEvent(object from, EventArgs args);

 We raise the event from the Publisher class

public void raiseEvent(EventArgs args)
{
theevent(this, args);
}

We trigger the event here 

 public void SendTheEvent()
    {
        MessageBox.Show(“the event is fired here”);
        this.raiseEvent(new EventArgs());
    }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Publisher.cs file add this bit of code, using System.Windows.Forms.

4) Add another class file to the project and call it Subscriber.cs. Add the code below in the class Subscriber

public Subscriber()
 {

Publisher myclass = new Publisher();
     
myclass.theevent += new Publisher.DelegateEvent(handletheevent);

myclass.SendTheEvent();

}

Let me explain what I do here

We create an instance of the Publisher class

Publisher myclass = new Publisher();

We want to subscribe to this event delegate (DelegateEvent) of Publisher. So if the Publisher
raises any event, our method called the “handletheevent” is notified

myclass.theevent += new Publisher.DelegateEvent(handletheevent);

The event is fired here

myclass.SendTheEvent();

our event handler code goes here that responds to the event being fired

   private void handletheevent(object sender, EventArgs e)
   {
    
       MessageBox.Show(“Event handled in handletheevent of the Subscriber”);
    
     
       MessageBox.Show(“Who is the Sender?” + sender.GetType());
   }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Subscriber.cs file add this bit of code, using System.Windows.Forms.

5) Run your application and see the results

Hope it helps!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Comments»

1. suyog - February 18, 2009

hi this is good one

2. Hichem - May 12, 2009

I think that is give me some things about my problem

3. Object Oriented Programming Concepts with C#3.0 « DOT NET RULES - June 21, 2009

[…] more information on this topic have a look at this post of […]

4. Lambda Expressions with VB.Net « DOT NET RULES - June 25, 2009

[…] expressions are shorthand for anonymous delegates . Basically delegates allow you to create a variable that “points” to a method. We can use this […]

5. prakash - January 7, 2010

hi very useful article. thanks

6. parveen - May 27, 2010

very good articles about the deletgates

7. sampath - January 8, 2011

Ir is very useful topic tan q……….

8. vishal patwardhan - April 8, 2011
9. hassan - May 4, 2011

Thanks alot

10. Nilesh Bawalekar - May 25, 2011

Great article..Thank you.


Leave a comment