What is a Delegate?
When we talk about delegates in .NET then one thing that comes to our mind is what delegate means to a novice developer. In simple words we can say delegates are a .NET object which points to a method that matches its specific signature.
In other words delegates are function pointers that point to function of matching signatures. Function pointers which are extensively used in c/c++ to points to a function holds only the memory address of the function, it doesn’t carry further information about the function parameters, return type etc. On the other hand .NET framework has introduced a type-safe mechanism called delegates, with automatic verification of the signature by the compiler.
So comparatively delegates add a safety dimension in handling function pointers in .NET.
So we can say that delegates are type-safe, object oriented, secure .NET objects which can be used to invoke methods of matching signature.
While using delegates it is very much necessary to make sure that the functions which the delegates points has the same number of argument type and same return type. For example if we have a method that takes a single string as a parameter and another method that takes two string parameters, then we need to have two separate delegate type for each method.
Types of Delegate
Delegates are of two types:
Single cast delegate
A delegate is called single cast delegate if it invokes a single method. In other words we can say that SingleCast Delegates refer to a single method with matching signature. SingleCast Delegates derive from the System.Delegate class
SingleCast Delegates can be defined using the following syntax:
In the above code I have defined a delegate which can encapsulate a method that takes two parameters of type integer and then returns an integer as a return type.
Let’s look at an example of SingleCast Delegates to see their implementation.
Listing 1: Single cast delegate example
Explanation
In the above code snippet I have declared a single delegate which takes two integer type as arguments and returns an integer as return type.
At runtime I have created a delegate variable as singleCastMaxNumberDelegate of type mySingleCastDelegate. Using the delegate variable, I can point to any method that has the matching signature.
In the above example the method myMaxFunction has the matching signature with the delegate variable. So using the new keyword I have referenced the delegate variable to the myMaxFunctionf:
Now I can call the function myMaxFunction by passing required parameters through the delegate.
When we run the above code snippet, we get the result as follows:
Figure 1: Single cast delegate result

Multicast Delegates
MultiCast Delegates are nothing but a single delegate that can invoke multiple methods of matching signature. MultiCast Delegate derives from System.MulticastDelegate class which is a subclass of System.Delegate.
In Multi-Casting basically we create a single delegate that in turn invokes multiple encapsulated methods. We can use MultiCast Delegates when multiple calls to different methods are required. For example if we are required to call two methods on a single button click event or mouse over event then using MultiCast Delegates we can easily call the methods.
The System.MulticastDelegate class provides required methods to play with delegates. There are two methods, Combine and Remove, which are used to play with delegates.
The Combine method is a static method of System.MulticastDelegate class which is used to combine the delegates and the Remove method is used to remove the delegate from the list.
The Combine method takes an array of delegate as a parameter and returns a new delegate that represents the combination of all the delegates in the array.
MultiCast Delegate can have arguments and can have return values as well. The only things is that the methods pointed by delegate needs to have same return type as that of the return type of delegate.
In the below code snippet I have defined a delegate which can act as a multicast delegate to encapsulate methods that takes two parameter as of type integer and returns nothing.
Let’s take an example of MultiCast Delegate to see how multiple methods can be called.
Listing 2: Multi cast delegate example
Code Explanation
There are two functions declared, myAddtionfunction and myMaxFunction. Both of theses functions take two integer type as parameters and return void. I have created three delegate variables of type MultiCast Delegate, out of which myDelegate assigned with null value where as the other two delegates referenced to each of two functions.
I have used the Combine method of system.delegate to combine the two delegate variables.
System.Delegate provides another method, remove, which can be used to remove the specific delegate from the list. Here the remove function is being used to remove the myMultiCastDelegateMaxNumber function from myDelegate list
When we run the above code snipet, then we get the following result:
Figure 2: Multicast Delegate example

Event handling using delegates
In a sense we can say that an event is a resultant outcome of an action. In programming terms, when a user does some actions on a User Interface such as clicking a button or hover a mouse on an image then some things happen on the user interface, like some pop up opens up or the page posts back to server etc. In this sense if clicking a button is an action then the outcome of that action is an event.
In the .NET Framework an event enables objects in a class to notify other objects that an action has been performed and that they should react. Events in the .NET Framework are based on the publisher-subscriber model. Publisher of the event is the class that publishes an event and the subscriber of the event is the class that registers to the published event. In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified.
In the event communication process the publisher doesn’t know who is going to subscribe the event. Under this circumstance delegates play a handy role to act as an intermediary between the publisher and the subscriber.
The following example describes the methodology by which delegates can be used in event handling in C#.NET.
Listing 3: Event handling using delegate example
Explanation
In the MyDelegateClass I have used the following line to declare the event handler which is nothing but a delegate having two parameters: (object sender, MyEventArgs e).
The first parameter denotes the object which is the source of the event; that is, the publishing object. The second parameter is an object derived from MyDemoEventArgs class which containes information about the event data.
The class MyDemoEventArgs is derived from the class EventArgs. EventArgs is the base class of more event specialized classes containing event data, like MouseEventArgs, NavigateEventArgs, etc. In a GUI event we can use the objects of these specified EventArgs class where as for a non GUI event we need to create our own customized EventArgs class to hold the data that can be passed to the delegate object.
The following code is used to create our own customized EventArgs class.
Next I have declared a public event called MyEvent of type MyFirstEventHandler delegate.
The function FireMyFirstDemoEvent(string strMyEventArgs) is the entry point of our event. This function creates the EventArgs instance and then raises the event by passing the EventArgs object.
The method RaiseMyDemoEvent(MyDelegateClass objDelegate) present in the MyEventHandlerClass adds a delegate containing the method MyEventHandlerFunction(object sender, MyDemoEventArgs e) to the class event. When the event is raised it will subsequently execute MyEventHandlerFunction() method.
In the main function I have created the instances of the class that fires the event and an instance of the class that handles the event.
When we run the sample code snippet, we get the following result:
Figure 3: Event Handling example

Conclusion
In my conclusion I can say that Delegates are an important feature of .NET with respect to handling events. If you are using Visual Basic .NET then it is not required at all to create delegates while dealing with events because With Events and AddHandler keywords take care of all the details under the hoods. Also, Delegates play a useful role in situations where you need to execute a particular action without knowing the method you would be calling upon to execute the action.
About Rupesh kumar Nayak
 |
Rupesh is working in a leading IT Company in India as a software engineer, he started his journey from scripting language PHP and MySQL and later on moved to Microsoft's .Net technology.His area of expertise including PHP, ASP,VB.net, C#.Net, XML, HTML, JavaScript, AJAX, SQLReporting2002, SQLRe...
View complete profile
|
Top Articles in this category
Introduction to 3-Tier Architecture
Brian Mains explains the benefits of a 3-tier architecture.
Settings Manager for Windows Vista Sidebar Gadgets
SettingsManager is a JavaScript library that allows Windows Vista Sidebar gadgets to persist common settings that all gadget instances have access to.
ORM in .NET 3.5
This article covers a general introduction to ORM concepts, the approach that .NET 3.5 takes, and how it compares to these other packages.
SuperToolTip
Office 2007 offers great new features, one of them is the SuperTooltip which provides much more information about controls than standard old style tooltips. This article shows how to build tooltips in such a way.
Barcode image generation made easy
In this article we are going to generate barcodes in .NET. Barcode-aware devices, such as scanners and printers, are readily available on the market, as long as the barcodes we generate follow the standards.We will implement barcode generation using Microsoft Ajax in a web application.
|
|
Please login to rate or to leave a comment.