Understan delegates in C Sharp (Viewed - 1311 times)



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) 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 customDelegate(int thefirst,int thesecond);

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

TheClass theClass = new TheClass();
customDelegate delegateAddition = new customDelegate(theClass.addnumbers);
int addition = delegateAddition(10, 89);
Response.Write(“<br />”);
Response.Write(addition.ToString());


I will try to explain what the code does.

customDelegate delegateAddition = new customDelegate(theClass.addnumbers);

I have created a delegate variable(delegateAddition) of type customDelegate. 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.







  Liked us?