KnowDotNet NetRefactor

Creating and Handling Events - Part 1

by Brian Davis
Print this Article Discuss in Forums

Every .NET developer has handled events from controls or other objects, but have you written your own events to be raised and handled by your classes?  It is easy to do, and it is a vital tool for the .NET developer.

Part 1 of this tutorial on events will focus on creating and raising a simple event.  The first step in creating an event is to determine whether or not there is any data that should be associated with the event.  For example, a class named
Car may have an event that is raised when the Car is started.  There is not really any data associated with this event, we just want to know that the Car started.  The first thing we do then is declare an event within the Car class:

VB
Public Event Start As EventHandler

C#
public event EventHandler Start;


Once the event is declared, we need to have the ability to raise it.  In C#, we will need to create a special method for this.  This method checks to see if the event can be raised and then raise it.

C#
protected virtual void OnStart(EventArgs e)
{
  
if(this.Start != null)
   {
      
this.Start(this, e);
   }
}

To raise the event in C#, we call this new method, passing a default instance of the EventArgs class.

C#
this.OnStart(new EventArgs());

To raise the event in VB, we simply use the RaiseEvent keyword, indicating the event that should be raised and passing a default instance of EventArgs.

VB
RaiseEvent Start(Me, New EventArgs)


Putting all of this together, here is what our Car class would look like:

VB
Public Class Car

  
Public Event Start As EventHandler

  
Public Sub StartEngine()
      
' *** CODE TO START ENGINE ***

     ' Raise event to notify others
     RaiseEvent Start(Me, New EventArgs)
  
End Sub

End
Class

C#
public class Car
{
  
public event EventHandler Start;

  
protected virtual void OnStart(EventArgs e)
   {
      
if(this.Start != null)
      {
        
this.Start(this, e);
      }
   }

  
public void StartEngine()
   {
      
// CODE TO START ENGINE

      
// Raise event to notify others
     this.OnStart(new EventArgs());
   }
}


That's it!  That is all that you need to begin raising your own custom events from your classes.  In
Part 2 of the tutorial, we will learn how to create events that require additional data.


Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing