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:
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 :
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.
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.
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.
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.
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.