Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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 should ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata