C# Events Explained (Page 1 of 6 )
It's time to discuss events in C#, since we had a good simple discussion about C# delegates in the past article. Today we explain what events are, how they are implemented, why they are exist and when to use them.
I will show you how to create something that is event-like without an event and why it's a bad practice; I show you this technique to help you understand the design of .NET events. Also we will look at the conventions of naming our classes and methods that form the event model. If you are not familiar with delegates I suggest reading my article "C# Delegates Explained" because the concepts and techniques discussed here are based on that article.
As you may remember from the discussion in the previous article, C# Delegates Explained, a delegate is an object that refers to a method, and we call this method by invoking the delegate itself. If you think about this for a minute you will realize that the event model is based on delegates. You must be familiar with events. An event is simply a notification of something that took place, such as a Windows form being loaded, a mouse button being clicked, a book being added to the book shop and other numerous behaviors.
We need a way to take some actions when an event is fired (or we can say took place) and this is introduced in C# through the use of delegates and event handler methods as we are going to see shortly. The event model is designed so that an object fires an event and another object (or objects) watches the occurrence of this event and calls a method to perform the action needed. The object that fires the event is called the publisher of the event and the object that has the method, which is called an event handler method, that is called when the event takes place is called the watcher object.
How do delegates fit into the game? The publisher object doesn't know which event handler method of which watcher object needs to be called when the event takes place. Through the use of delegates any object (such as the watcher object) that needs to be notified about the occurrence of the event will have to create a new instance of a delegate (the type of the delegate is discussed later) that refers to the event handler method, then assigns (thus subscribing) this delegate to the publisher object's event. The event maintains a multicast delegate, and when the event takes place the multicast delegate invokes its invocation list of delegates, causing all the subscriber objects' (the watcher objects') event handler methods to be called.
I know that you may be confused about how it's done, but by the end of this article you will understand the usefulness of delegates and events together. Let's begin with a very simple example, a Windows Form example.
Next: The Windows Form Example >>
More C# Articles
More By Michael Youssef
|
| · | | · | | · | | · | | · | | · | | · | | · | | · | | · | | · | | · | | · | | · | | | | |
|