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 |
| public event EventHandler Start; |
| protected virtual void OnStart(EventArgs e) { if(this.Start != null) { this.Start(this, e); } } |
| this.OnStart(new EventArgs()); |
| RaiseEvent Start(Me, New EventArgs) |
| 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 |
| 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()); } } |