C# Events Explained - The Steps of Creating an Event
(Page 3 of 6 )
The very first step in creating an event is to define the signature of the event handler methods of the watcher objects in a delegate type. Why? Because events are based on delegates which encapsulate methods with a specific signature. As you know .NET Delegates are type-safe. Then you create a class that raises the event, the Publisher. In this class you define the event of the specific delegate type using the event keyword then define a method that fires the event. The last step is to create a watcher object that has an event handler method that will be called when the event takes place.
Let's assume that we have a bookshop which fires an event each time a book is added to the bookshop. Another object needs to be notified each time a book is added to the bookshop to send the members an e-mail message to tell them about the new book. We need the following classes in order to create an event-based application:
The Book class which represents a book.
The BookShop class that fires the event.
The AddBookEventHandler Delegate type that defines the signature of the event handler methods.
The BookEventArgs class to carry the event data.
The Notifier class which represents the watcher object.
The Sys class that contains the Main() method which creates the objects and test the event.
Let's create those classes step by step.
The Book Class
The Book class is very simple. It has three private fields with their public properties and one constructor.
public class Book
{
private string title;
private string isbn;
private decimal price;
public Book(string title, string isbn, decimal price)
{
this.title = title;
this.isbn = isbn;
this.price = price;
}
public string Title
{
get{return this.title;}
}
public string ISBN
{
get{return this.isbn;}
}
public decimal Price
{
get{return this.price;}
}
}
Next: The Bookshop Class and the AddBookEventHandler Delegate >>
More C# Articles
More By Michael Youssef
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|