Total votes: 2
Print: Print Article
Please login to rate or to leave a comment.
Published: 18 Jul 2008
Rupesh Kumar Nayak explains delegates in .NET.
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.
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.
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
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
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
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
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 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
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.
System.MulticastDelegate class provides required methods to play with delegates. There are two methods,
Remove, which are used to play with delegates.
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.
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
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
There are two functions declared,
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
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.
MyDemoEventArgs is derived from the class
EventArgs is the base class of more event specialized classes containing event data, like
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
FireMyFirstDemoEvent(string strMyEventArgs) is the entry point of our event. This function creates the
EventArgs instance and then raises the event by passing the
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
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
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.
This author has published 2 articles on DotNetSlackers. View other articles or the complete profile here.
Please login to rate or to leave a comment.