C# Events Introduction


This entry is part 1 of 5 in the series C# Events

The post C# Introduction lists all of the C# series of posts we have at this site.

Sometimes you need to work with events. When an event occurs, another part of the program needs to be notified that the event has occurred. An event is a mechanism for communication between objects. Events help us build loosely coupled applications. It helps us extend applications.

We could put some code in our class that calls a method that sends a message. The problem is that in future we want to send a different message. We would need to add an extra line of code to send that message. The problem with this is that we need to add the line of code and recompile it. Perhaps we need to send an object a message.

Another way to do this is to use the pattern publisher/subscriber pattern. A class called the publisher defines a set of events that other parts of the program might be interested in. Other classes can then “sign up” for notifications by supplying a method to the publisher. When the even occurs, the publisher “raises an event” and all the methods submitted by the subscribers are executed.

We need an agreement between the publisher and the subscriber. The publisher will call a method when an event happens, but it knows nothing of the subscribers. To do this we use a delegate. A delegate is an agreement between the publisher and the subscriber.

Delegates were covered in a previous post. Many aspects of events are similar to those of delegates. In fact, an event is like a simpler delegate that is specialized for a particular use. There’s good reason for the similarities in the behaviors of delegates and events.

Delegates

  • A delegate is a pointer to a function/method or group of functions with a specific signature.
  • A delegate is an object that contains an ordered list of methods with the same signature and return type. The list of methods is called the invocation list.
  • A delegate is an object that holds one or more methods. A delegate is different from a typical object. You can execute a delegate, and when you do so, it executes the method or methods that it “holds.”
Series NavigationC# Events Example >>