Understanding delegates

A delegate is nothing but a reference to a method, along with some parameters and a return type. When a delegate is defined, it can be associated with any instance that provides a compatible signature and a return type of the method. In other terms, delegates can be defined as function pointers in C and C++. However, delegates are type-safe, secure, and object-oriented. 

A delegate model follows the observer pattern, which allows the subscriber to register with and receive notifications from the provider. To get a better understanding of the observer pattern, take a look at the references provided at the end of this chapter, in the Further reading section.

A classic example of a delegate is event handlers in a Windows application, which are methods that are invoked by delegates. In the context of events, a delegate is an intermediary between the event source and the code that handles the event.

Delegates are ideal for callbacks because of their ability to pass methods as parameters. Delegates are derived from the System.Delegate class.

The general syntax of delegate is as follows:

delegate <return type> <delegate name> <parameter list>

An example of a delegate declaration is as follows:

public delegate string delegateexample (string strVariable);

In the preceding example, the delegate that's been defined can be referenced by any method that has a single string parameter and returns a string variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.213