Name

Delegate

Synopsis

A delegate is used to provide a decoupling of caller from callee; that is, a delegate points to a given method (instance or shared) in a class, and callers can call through the delegate without having to know the target of the call. In many respects, the delegate is conceptually similar to the C/C++ function pointer, with a number of important advantages. A delegate is strongly typed, meaning that only methods that match the delegate’s declared signature are acceptable when constructing the delegate instance, and the compiler enforces the delegate’s declared signature when called. A delegate can distinguish between a shared and an instance method. This avoids the C++ application associated with pointers to member functions, which require a literal pointer to the object upon which to invoke the method.

Delegates are usually constructed by the language compiler, varying in syntax from language to language. In VB.NET, the construct Public Delegate Sub CallBackDelegate(param1 as Integer, param2 as String) declares a new type that derives from the Delegate type (its immediate superclass is actually MulticastDelegate). This new CallbackDelegate type is also declared with a constructor (to take the method to call when the delegate is invoked) and an Invoke method (to do the actual call), along with asynchronous versions of Invoke (the BeginInvoke and EndInvoke methods).

In many cases, you will want to use delegates as an invocation chain, where a single call to ...

Get VB.NET Core Classes in a Nutshell 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.