Developer

Get the hang of custom events in C#

In our continuing series for C# beginners, we'll walk you through creating custom events. See how to implement these key C# components by building a delegate and adding an event handler.


If you are new to C#, one of the most important language features you need to master is working with events. In part one of this series, we discussed the basics of C# events and illustrated how to use the Events tab of the Properties window. We also ran through the autogenerated code that using the Events tab creates.

Now let's cover creating custom events. We'll walk through a project that illustrates how custom events are fired and how your code responds to them.

More C# articles by Harold Davis


Custom event steps
Let's consider the example of an event that's fired if a long integer passed to a method is a prime number. The method will be placed in a class module, although it could also reside in the Form class, since in .NET a form is just an instance of a class. We'll use the form we developed in the first part of this series to both invoke the method that fires the event and respond when the event is fired.

Here are the steps we'll need to take to make this work:
  1. 1.      Add a class module to the project.
  2. 2.      Add a method to the module that checks to see if the number passed to it is prime and, if so, fires an event.
  3. 3.      Create a delegate in the form (the receiving class).
  4. 4.      Associate the delegate with the event.
  5. 5.      Add the event handler framework to the Form class.
  6. 6.      Use the += operator to notify the receiving class instance (the form) that the event handler in the receiving class instance should be invoked when the event is fired in the class module.
  7. 7.      Add code to the event handler that responds appropriately to the event.

Let’s run through these steps from the top.

Adding a class and method
You can add a class module to a C# project using several methods. One is to open the Add New Item dialog box by selecting Add Class from the Project menu. Make sure that Class is selected in the Templates pane, as illustrated in Figure A, and click Open.

Figure A
Select the Class template.


The new bare-bones class, with a class constructor and nothing else, will look like Listing A. For clarity, I’ve removed the autogenerated comments from our example.

As shown in Listing B, add a method to this class that checks to see if the number passed to it is prime.

Give the name OnPrime to the event that is fired when a prime number is found. Here’s how the IsPrime method looks with the OnPrime event fired. Note that the event passes the prime number as a parameter, as you can see in Listing C.

Declaring delegates
Next, you declare a delegate in the class for the OnPrime event. This declaration can go anywhere within the class module. Note that you don’t really need to create a delegate, especially for an event method, if its signature matches the built-in System.EventHandler delegate. However, it 's good practice to declare a delegate for each custom event. You'd have to do so in our example because of the added parameter (the prime number found) in the signature.

Here’s the delegate declaration:
public delegate void OnPrimeEventHandler (object sender, System.EventArgs e, long num);

Next, associate the delegate with the event:
public event OnPrimeEventHandler OnPrime;

The class module is now complete, although until you create the code in the receiving class, it doesn’t do anything useful. However, if you run the project, you should see no syntax errors. Listing D provides the complete code for the class module.

The event handler
Returning to the receiving class, which happens to be a form class (but, as I noted earlier, need not be), let’s add an event handler. Here’s what it looks like:
private void Class1_OnPrime (object sender, System.EventArgs e, long theNum){
}


Notifying the firing class
Next, add a notification to the instance of the class module so that the code placed in the event handler is processed when the event is fired. Before doing this, we’ll need to create an instance of Class1 in the form class. Then, create a button named btnDoPrimeThing; you'll place the code to be executed in the Button’s click event and display the rest in a multiline text box.

Listing E shows the code in the click event that creates an instance of Class1 and tells the event in the class to notify our event handler when the event is fired.

Adding code to the event handler
Finally, let's add code to the button click event that causes the custom event to be fired, and to the form event handler that responds to the event.

Listing F shows the code added to the Button click event that invokes the IsPrime method for the integers from 1 to 100.

Finally, you need to add code to the event handler to ensure that your event fires. Each prime number that fires the event is displayed in the text box, as shown in Listing G. Figure B illustrates what the final results should look like.

Figure B
The finished project displays a list of primes in the text box.


I’ve included the project discussed in this article as a downloadable zip archive, should you want to inspect the full source code. To install the project, unzip it into a directory on a machine that is running Visual Studio, and double-click the .sln file's Windows Explorer icon.

A basic building block
Events are a central feature to an object-oriented language like C# and can play a significant role in the architecture of projects. While there are quite a few details involved in programming events, if you keep the concepts, context, and order of components clear, you shouldn’t have too many problems getting the hang of this key feature.

 

Editor's Picks