Delegates in C#
Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.
Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.
In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.
.NET implements the concept of function pointers using delegates.
- Delegate wraps a method. Calling delegate results in calling the method.
- Delegate is a type of object very similar to classes.
- Delegate gives a name to a method signature.
.
Where are Delegates used?
The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.
Starting Threads/Parallel Processing:
You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate.
Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates.
Creating and Using Delegates:
Using delegates is a two step process-
……….1) Define the delegate to be used
……….2) Create one or more instances of the delegate
Syntax for defining a delegate:
delegate string reviewStatusofARegion();
to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters.
Syntax for creating an instance of the delegate:
reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope)
private string getEurope()
{
return “Doing Great in Europe”;
}
To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name.
The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error.
Multicast Delegate:
Delegate wraps a method. Calling delegate results in calling the method. It is possible to wrap more than one method in a delegate. This is known as a multicast delegate.
If you make a call to a multicast delegate it will call all the functions it wraps in the order specified. Please note that functions in this case should not return any values.
Syntax for defining a delegate:
delegate void deleteRowsinTable( int Year)
Syntax for instantiating the delegate:
deleteRowsinTable Cleanup = new deleteRowsinTable(archiveCompletedTasks)
Cleanup += new deleteRowsinTable(purgeCompletedTasks)
Using Delegates in Event Handling
Events could be visualized as following:
Example: You setup a wakeup alarm in your clock for 6 a.m.
Hence you need a class/object that creates and fires an event
You need a mechanism to notify all
You need a method to listen for the notification
Finally, you need a method that does something when the notification is received.
Another example
Here is how you code for it
Create a class called Mylist
1) Declare an Event public event System.EventHandler EventName;
2) Declare a method that creates the event protected virtual void OnEventName(System.EventArgs e) 3) Fire the Event when appropriate conditions are met by calling the above method
If (condition met) {protected virtual void OnEventName(System.EventArgs e);}
Now you have a class that has the event definition, triggers an event when appropriate condition occurs and notifies every one.
Next, Create a class EventListener
1) Create a variable of type MyList
2) Create a method that shows a message box
3) Create constructor which takes a parameter of type MyList
4) In the constructor add the method you created in step 2 as an eventhandler for the event ( See Code below)
5) Add a method to remove the method from the event handler
Now you have a class that handles the event and does something when the even occurs
Next, create a class in a console application to test all of the above
1) Create an instance of the list
2) Create the event handler
3) Add an Item to the list
4) See the Results
The results shown below
Summary:
In this article we studied the basics of delegates and Event handling in C#