Click here to Skip to main content
15,881,516 members
Articles / Programming Languages / C#
Article

Events and Delegates

Rate me:
Please Sign up or sign in to vote.
3.84/5 (71 votes)
6 Jun 2004CPOL5 min read 104.4K   1.3K   67   18
Events and Delegates - A real time approach.

Introduction

One of the most interesting concepts in C# is Event-Driven approach. Though it is a simple technique, this article is here for beginners and those who are struggling to understand the event driven model.

Delegates

Delegation model is a process in which a task is handed over to some other process so as to accomplish it. A manager is assigned a job which could be executed by one of his subordinates. As he knows the exact location of the subordinate, he redirects or delegates the work. Here, manager is the delegate and his subordinate is the method wrapped up with the delegate.

Delegates are the special objects in C# which are pointers to methods. It’s an interesting and amazing feature of C#. It is something that gives a name to a method signature. These are implemented as classes derived from the base class System.Delegate. It is nothing but a type like a class. But with classes, there are two distinct terms: 'class', which indicates the broader definition, and 'object', which means an instance of the class. Unfortunately, with delegates, there is only the one term. That is, when you create an instance of a delegate, what you have created is also referred to as a 'delegate'. The syntax for defining delegates looks like this:

C#
delegate <return type> <delegate name>( <parameter list> );

The important point to note here is the signature of delegates and methods. A software team manager will lead a group of people whose educational background is related to information technology and who can develop and maintain software applications. Hence, the method to be wrapped must match the signature of the delegate, otherwise would end up with a compilation error.

Multicast Delegate

Any manager in an organization will have one or more subordinates working under him. When a task is to be accomplished, the chief will not call each and every subordinate individually. Because, the chief does not know the specialization of all the subordinates. The chief will instruct or assign a task to the manager and the manager in turn will delegate the work to his subordinates. Obviously, any number of subordinates could be added or removed from a particular team at any point of time.

When a delegate is wrapped with more than one method, that is known as a multicast delegate. As stated above, a manager who points to more than one member is a multicast delegate. If a multicast delegate is called, it will successively call each method in order. It is derived from System.MulticastDelegate that in turn is derived from System.Delegate. System.MulticastDelegate has additional members to allow chaining of method calls together into a list.

Event

Events are nothing but change of state. Assume that a software project was successfully installed in a customer's place. Later, the maintenance department was notified by the client for some enhancements. It’s an event and which triggers the corresponding manager to take necessary actions, and he handles it by delegating the task to his subordinates. Here, make a note of two key aspects, i.e., event and event handlers. The client's requisition for modification is 'event' and the subordinates who are going to execute that requisition are 'event handlers'.

Events are actually a special form of delegates. It’s a way for server applications to provide notifications to clients of that class when some interesting thing happens to an object. It is extensively used in Graphical User Interfaces (GUIs). Events are declared using delegates. Considering the aforesaid example, event is a way for a server application to allow client applications to give it delegates to methods that should be called when the event occurs. When an event occurs, the delegate(s) given to it by its client applications are invoked. The syntax to declare an event is :

C#
event < delegate type name > < event name >;

Here event is the keyword, delegate type is the delegate you declared earlier, and the event name.

Stock Management Module

Here is the code which has four events and as many event handlers as you wish. This module contains 4 classes viz., CInventory, CInventoryManager, CInventoryWatcher, and CStockentry. Before going into the module, I would like to touch the stock management system. In the inventory control system of any item, we have stock level, reorder level, minimum and maximum level. When stock is beyond the maximum level, the purchase department should be informed to stop ordering new items. Likewise, when the stock reaches either minimum or reorder level, we raise the purchase order, and the same should be authorized so as to purchase new items. This is what this code explains.

The class CInventory is an entity class where the item name and stock value are maintained.

C#
private string _sStockName;
private int _iStock;

public string StockName
{get{return _sStockName;} set{ _sStockName=value;}}

public int Stock
{get{return _iStock;}set{_iStock += value;}}

CInventoryManager is the event publisher which has four events viz., OnInventoryChange, OnMaxLevel, OnROLevel, and OnMinLevel. Whenever there is a change in the stock value, OnInventoryChange will be triggered. Other events are raised based on a particular state. If the stock value is less than or equal to 20, OnMinLevel event will be triggered. If the stock value is less than or equal to 50, then OnROLevel event will be triggered. If the stock value is greater than or equal to 100, then OnMaxLevel event will be triggered.

C#
public delegate void InvDel(object source,CInventory inventory);

public event InvDel OnInventoryChange;

public event InvDel OnMaxLevel;

public event InvDel OnROLevel;

public event InvDel OnMinLevel;

CInventoryWatcher class is the event subscriber where event handlers are placed. Here, you could see how multicast delegates are defined and executed. In the constructor of this class, you will find the event subscriptions by instantiating InvDel delegate which is located in CInventoryManager class. When OnROLevel event occurs, two event handlers subscribed to it will fire. Which means, whenever the stock value reaches reorder level, we have to create purchase order, and the purchased order should be authorized.

C#
inventoryManager.OnInventoryChange += new CInventoryManager.InvDel(OnChange);
inventoryManager.OnROLevel += new CInventoryManager.InvDel(CreatePO);
inventoryManager.OnMaxLevel += new CInventoryManager.InvDel(CreateMaxMsg);
inventoryManager.OnMinLevel += new CInventoryManager.InvDel(CreateMinMsg);
inventoryManager.OnROLevel += new CInventoryManager.InvDel(AuthPO);

Running the sample application

Run the sample application. In the stock entry form, enter the name of the item and the new stock value. I have coded the values for minimum, maximum, and reorder level. That is, Minimum level =20, Maximum Level =100 and Reorder Level = 50. If you want, you can change these values in the StockLevels.cs file. Please look at the source code for more clarifications. The whole task could be achieved in a single file, but to understand event generators and even handlers, I have separated it.

I would appreciate if you could give your valuable feedback after reading this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Spends his fulltime in Microsoft Technologies for more than 9 years. He likes OOAD Concepts and its implementaions and has written many articles on Object Oriented Programming in the regional magazines.

His recent experience was in Desktop/Web based application development using MS C#. He's fascinated by the language and the .Net framework.

Comments and Discussions

 
GeneralThanks for help! Pin
diedev10-Sep-10 16:42
diedev10-Sep-10 16:42 
GeneralThanks for the help Pin
Stephen McAllister24-Nov-05 13:37
Stephen McAllister24-Nov-05 13:37 
GeneralExcellent article!! Nice comparison to explain delegation concepts. Pin
1607111-Aug-05 7:14
1607111-Aug-05 7:14 
GeneralRe: Excellent article!! Nice comparison to explain delegation concepts. Pin
Navis Singarayan29-Nov-05 4:15
Navis Singarayan29-Nov-05 4:15 
GeneralCongrats! Pin
mstachura2-Aug-05 10:55
mstachura2-Aug-05 10:55 
GeneralA _good_ definition for DELEGATE for Java/Cpp programmers... Pin
Sigmundur Hakkarainen2-Aug-05 4:23
sussSigmundur Hakkarainen2-Aug-05 4:23 
Generalvery nice demonstration Pin
davidwei2-Jan-05 15:20
davidwei2-Jan-05 15:20 
GeneralOOPS Pin
iffi99212-Sep-04 15:36
iffi99212-Sep-04 15:36 
GeneralGreat article! Pin
Smitha Nishant17-Jun-04 21:39
protectorSmitha Nishant17-Jun-04 21:39 
GeneralThanks Pin
Navis Singarayan18-Jun-04 18:46
Navis Singarayan18-Jun-04 18:46 
GeneralThis article is great and deserves more rating! Pin
killerslaytanic11-Jun-04 5:19
killerslaytanic11-Jun-04 5:19 
GeneralThanks Pin
Navis Singarayan13-Jun-04 23:37
Navis Singarayan13-Jun-04 23:37 
GeneralExcellente Article Pin
FredyAlfredo7-Jun-04 22:57
FredyAlfredo7-Jun-04 22:57 
GeneralThanks Pin
Navis Singarayan10-Jun-04 19:47
Navis Singarayan10-Jun-04 19:47 
GeneralRiped Fruit Pin
Rajchandar .R7-Jun-04 2:02
Rajchandar .R7-Jun-04 2:02 
GeneralRiped Fruit Pin
Navis Singarayan10-Jun-04 19:48
Navis Singarayan10-Jun-04 19:48 
GeneralReally excellant Pin
jrangarajan7-Jun-04 0:58
jrangarajan7-Jun-04 0:58 
GeneralThanks Pin
Navis Singarayan10-Jun-04 19:49
Navis Singarayan10-Jun-04 19:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.