Wednesday, December 12, 2007

Creating Custom Delegates and Events in C #

Creating Custom Delegates and Events in C #

Controls used on your forms have events associated with them you can respond to with event handlers in your application. C# makes it easy to have the same behavior in other parts of your application by creating your own delegates and events, and raising the events based on your program logic.

There are three pieces that are related and must be included to make our custom events work. They are a delegate, an event, and one or more event handlers. In this article we will examine delegates and events, how they relate, and how to use them to create custom event handling for your applications. The code to implement the delegates and events is also shown. Details about the code are included in comments.
Delegates
A delegate is a class that can contain a reference to an event handler function that matches the delegate signature. It provides the object oriented and type-safe functionality of a function pointer. The .NET runtime environment implements the delegate; all you need to do is declare one with the desired signature. It is customary for delegates to have two arguments, an object type named sender and an EventArgs type named e.

When you double click on a control in the forms designer of Visual Studio.NET, you are provided with a stub for an event handler that matches this signature. This signature is not required and you may want a different signature for your custom events. When a delegate is created and added to an event invocation list, the event handler is called when the event is raised. Multiple delegates can be added to a single event invocation list and will be called in the order they were added.
Events
Events are notifications, or messages, from one part of an application to another that something interesting has happened. When an event is raised, all the delegates in the invocation list are invoked in the order they were added. Each delegate contains a reference to an event handler, and each event handler executed. The sender of the event does not know which part of the application will handle the event, or even if it will be handled.

It just sends the notification and is finished with its responsibilities. It is often necessary to provide some information about the event when the notification is sent. This information is normally included in the EventArgs argument to the event handler. You will probably want to develop a class derived from EventArgs to send information for custom events.
Suppose you are creating an application for a bank to manage accounts and want to raise an event when a transaction would cause the balance falls below some minimum balance. There is no button to click when this happens, and you would not want to depend on a person noticing the balance is low and performing some action to indicate the balance is low to the rest of the application.

A low balance happens because of a withdrawal of some amount that reduces the account balance below the minimum required balance. You want the notification to be automatic, so appropriate action can be taken by some other part of the application without user intervention. This is where custom delegates and events are useful. The C# code below will demonstrate how to use delegates and events for this example.
First, create a class for our event arguments that is derived from EventArgs. We will include properties for the account number, current balance, required minimum balance, a message describing the event, and a transaction ID. You can include any information that would be useful for you application.
public class AccountBalanceEventArgs : EventArgs
{
private string acctnum;
public string AccountNumber
{
get
{
return acctnum;
}
}
private decimal balance;
public decimal AccountBalance
{
get
{
return balance;
}
}
private decimal minbal;
public decimal MinimumBalance
{
get
{
return minbal;
}
}
private string msg;
public string Message
{
get
{
return msg;
}
}
private int transID;
public int TransactionID
{
get
{
return transID;
}
}
// AccountBalanceEventArgs constructor
public AccountBalanceEventArgs(string AcctNum, decimal CurrentBalance,
decimal RequiredBalance, string MessageText, int transactionID)
{
acctnum = AcctNum;
balance = CurrentBalance;
minbal = RequiredBalance;
msg = MessageText;
transID = transactionID;
}
}
Now create the delegate. Our delegate will have a return type of void and take an instance of our AccountBalanceEventArgs class as the only argument. The delegate does not have to be declared inside a class. All our event handlers will have the same signature as this delegate. In other words, they will return void and take a single AccountBalanceEventArgs argument.
public delegate void AccountBalanceDelegate(AccountBalanceEventArgs);
Our next task is to create a class containing one or more methods that will raise the event if the correct conditions exist in the application logic. In this example, an instance of Account will raise the AccountBalanceLow event when a transaction, if completed, would cause the current balance of the account to fall below the required minimum balance. The event is included in the class.
public class Account
{
// Create an event for the Account class
// It has the form public event delegateName eventName
public event AccountBalanceDelegate AccountBalanceLow;
private string acctnum;
private decimal balance;
private decimal minBalance;
// This method could cause the balance to fall below the required minimum.
// We will raise the event if the balance is not high enough to withdraw
// amount without falling below the required minimum balance.
// transID is some extra information about which transaction caused
// the event to be raised, so it will be included in the event arguments.
public void Withdraw(decimal amount, int transID)
{
// if the transaction would reduce the balance below the minimum,
// raise the event
if ((balance - amount) < minBalance)
{
DispatchAccountBalanceLowEvent(transID);
}
else
{
// everything is ok, so reduce the balance and no event is raised
balance -= amount;
}
}
// This method adds an event handler (delegate) to the event invocation list.
// Any method that returns void and takes a single AccountBalanceEventArgs
// argument can subscribe to this event and receive notification messages about an
// AccountBalanceLow event.
public void SubscribeAccountBalanceLowEvent(AccountBalanceDelegate eventHandler)
{
AccountBalanceLow += eventHandler;
}
// This method removes an event handler (delegate) from the event invocation list.
// Any method that has already subscribed to the event can unsubscribe.
public void UnsubscribeAccountBalanceLowEvent(AccountBalanceDelegate eventHandler)
{
AccountBalanceLow -= eventHandler;
}
// This method raises the event, which causes all the delegates in the event
// invocation list to execute their event handlers. The event handlers are executed
// in the order the delegates were added.
private void DispatchAccountBalanceLowEvent(int transaction)
{
// make sure the are some delegates in the invocation list
if (AccountBalanceLow != null)
{
AccountBalanceLow(new AccountBalanceEventArgs(
acctnum, balance, minBalance,
"Withdrawal Failed: Account balance would be below minimum required",
transaction));
}
}
// the rest of the Account class implementation is omitted
}
Our final piece is to create a class with methods to handle the events. Name it whatever is meaningful for your application. Remember, the methods that will be event handlers for our event must have a signature that matches the delegate.
public class EventHandlerClass
{
// This method will be an event handler. It can be named anything you want,
// but it must have the same signature as the delegate AccountBalanceDelegate
// declared above.
public void HandleAccountLowEvent(AccountBalanceEventArgs e)
{
// do something useful here
// e.AccountNumber, e.AccountBalance, e.MinimumBalance,
// e.Message, and e.TransactionID are all available to use
}
// This method will be another event handler. It can be named anything you
// want, but it must have the same signature as the delegate
// AccountBalanceDelegate declared above.
public void HandleAccountLowEvent2(AccountBalanceEventArgs e)
{
// do something useful here
// e.AccountNumber, e.AccountBalance, e.MinimumBalance,
// e.Message, and e.TransactionID are all available to use
}
// the rest of the EventHandlerClass class implementation is omitted.
}
We now have all the code necessary to implement our custom event and have it handled by our event handlers. All we need is to tie everything together. Somewhere in your code, where it makes sense for your application, you would create instances of Account and EventHandlerClass, subscribe to the event notification, make a withdrawal and do something useful if the event is received.
// somewhere in your code create instances of the Account class
// and the EventHandlerClass class...
EventHandlerClass handler = new EventHandlerClass();
Account acct = new Account();
acct.SubscribeAccountBalanceLowEvent(
new AccountBalanceDelegate(handler.HandleAccountLowEvent));
acct.SubscribeAccountBalanceLowEvent(
new AccountBalanceDelegate(handler.HandleAccountLowEvent2));
// if the next line causes the current balance to fall below the mimimum
// balance, the event will be raised and handler.HandleAccountLowEvent will be
// called followed by handler.HandleAccountLowEvent2
acct.Withdraw(1000.00M, 1);
acct.UnsubscribeAccountBalanceLowEvent(
new AccountBalanceDelegate(handler.HandleAccountLowEvent2));
// now only handler.HandleAccountLowEvent will be called if the event is raised
acct.Withdraw(1000.00M, 2);
acct.UnsubscribeAccountBalanceLowEvent(
new AccountBalanceDelegate(handler.HandleAccountLowEvent));
// now no event handlers will be called
acct.Withdraw(1000.00M, 3);
If we needed to add another event to our code, most of the work is already finished. For example, if we wanted to add an AccountBalanceHigh event, we could use the same delegate and AccountBalanceEventArgs class.

We would need to declare the AccountBalanceHigh event, add the appropriate subscribe, unsubscribe and dispatch methods, create the event handlers, and raise the event when the balance for an account gets too high. If you look back over the code you can see it would take more time to implement the event handlers than to add the new event.
It is not difficult to implement our own delegates and events that allow us to send a notification that something interesting has happened from one part of our application to another. C# provides all the necessary tools to include this capability with a minimum of effort.

1 comment:

Karthikeyan VK said...

It was a nice eye opener for me ...