Joe has written an article for C# programmers wishing to create their own delegates and events in their C# applications with ease.
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.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More C# Articles
More By Joe E. Bennett
developerWorks - FREE Tools! |
The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration. FREE! Go There Now!
|
|
|
|
Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7. FREE! Go There Now!
|
|
|
|
Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase. FREE! Go There Now!
|
|
|
|
Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months. FREE! Go There Now!
|
|
|
|
Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components. FREE! Go There Now!
|
|
|
|
IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community. FREE! Go There Now!
|
|
|
|
Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable. FREE! Go There Now!
|
|
|
|
WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |