C Sharp

Delegates and Event Handlers

Another useful innovation of the C# language is something called delegates, which basically serve the same purpose as function pointers in C++. However, delegates are type-safe, secure managed objects. This means that the runtime guarantees that a delegate points to a valid method, which further means that you get all the benefits of function pointers without any of the associated dangers, such as an invalid address or a delegate corrupting the memory of other objects.

In this tutorial, we'll be looking at delegates, how they compare to interfaces, the syntax used to define them, and the different problems that they were designed to address. We'll also see several examples of using delegates with both callback methods and asynchronous event handling.

In tutorial "Interfaces," we saw how interfaces are defined and implemented in C#. As you'll recall, from a conceptual standpoint interfaces are simply contracts between two disparate pieces of code. However, interfaces are much like classes in that they're defined at compile time and can include methods, properties, indexers, and events. Delegates, on the other hand, refer only to single methods and are defined at run time. Delegates have two main usages in C# programming: callbacks and event handling. Let's start off by talking about callback methods.