O'Reilly logo

C# 2008 Programmer's Reference by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Delegates and Events

Two of the most important aspects of object-oriented programming are delegates and events. A delegate basically enables you to reference a function without directly invoking the function. Delegates are often used to implement techniques called callbacks, which means that after a function has finished execution, a call is made to a specific function to inform it that the execution has completed. In addition, delegates are also used in event handling. Despite the usefulness of delegates, it is a topic that not all .NET programmers are familiar with. An event, on the other hand, is used by classes to notify clients when something of interest has happened. For example, a Button control has the Click even, which allows your program to be notified when someone clicks the button.

This chapter explores the following:

  • What is a delegate?

  • Using delegates

  • Implementing callbacks using a delegate

  • What are events?

  • How to handle and implement events in your program

Delegates

In C#, a delegate is a reference type that contains a reference to a method. Think of a delegate as a pointer to a function. Instead of calling a function directly, you use a delegate to point to it and then invoke the method by calling the delegate. The following sections explain how to use a delegate and how it can help improve the responsiveness of your application.

Creating a Delegate

To understand the use of delegates, begin by looking at the conventional way of invoking a function. Consider the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required