Raise and Handle Events

Learn about the difference between methods and events and how delegates and events work in C#.

Let’s understand how methods perform actions on objects and how events, built on delegates, facilitate communication between objects, providing a powerful mechanism.

Methods and events

Methods are often described as actions that an object can perform on itself or related objects. For example, a List can add an item to itself or clear itself, and a File can create or delete a file in the filesystem.

Events are often described as actions that happen to an object. For example, a user interface Button has a Click event, a click that happens to a button. FileSystemWatcher listens to the filesystem for change notifications and raises events, like Created and Deleted, triggered when a directory or file changes. Another way of thinking of events is that they provide a way of exchanging messages between two objects. Events are built on delegates, so let’s start by looking at what delegates are and how they work.

Calling methods using delegates

We have already seen the most common way to call or execute a method: using the . operator to access the method using its name. For example, Console.WriteLine tells the Console type to call its WriteLine method. The other way to call or execute a method is to use a delegate.

Delegate as type-safe

If we have used languages supporting function pointers, think of a delegate as a type-safe method pointer. In other words, a delegate contains the memory address of a method that matches the same signature as the delegate so that it can be called safely with the correct parameter types.

Example

For example, imagine there is a method in the Person class that must have a string type passed as its only parameter, and it returns an int type, as shown in the following code:

Press + to interact
public int MethodIWantToCall(string input)
{
return input.Length; // it doesn't matter what the method does
}

We can call this ...