Events and Delegates

In C#, delegates are fully supported by the language. Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type.[15] You can encapsulate any matching method in that delegate.

You create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it, as in the following:

public delegate void ButtonClick(object sender, EventArgs e);

This declaration defines a delegate named ButtonClick, which will encapsulate any method that takes an object of type Object (the base class for everything in C#) as its first parameter and an object of type EventArgs (or anything derived from EventArgs) as its second parameter. The method will return void. The delegate itself is public.

Once the delegate is defined, you can encapsulate a member method with that delegate by instantiating the delegate, passing in a method that matches the return type and signature.

For example, you might define this delegate:

public delegate void buttonPressedHandler(object sender, EventArgs e);

That delegate could encapsulate either of these two methods:

public void onButtonPressed(object sender, EventArgs e)
{
    MessageBox.Show("the button was pressed!");
}

or:

public void myFunkyMethod(object s, EventArgs x)
{
     MessageBoxShow("Ouch!");
}

As you'll see later, it can even encapsulate both at the same time! The key is that both methods return void and take two properties, an object and an EventArgs ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.