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 static) 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 static 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 C#, the construct public delegate void CallbackDelegate(int param1, string param2); 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 the delegate ...

Get C# 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.