C# .NET Delegates : Definition and Purpose
A delegate is an abstraction of one or more function pointers. Delegates are derived from System.MulticastDelegate, which is a reference type. System.MulticastDelegate is derived from System.Delegate. The delegate classes offer a public interface for initializing, adding, removing, and invoking delegates. An instance of a delegate is an object that abstracts the semantics of a function pointer. The object encapsulates a function pointer and a target object. When a delegate is invoked, the delegate calls the function on that object.
Delegates have a signature and a return type. A function pointer dropped into the delegate must have a compatible signature, which makes the function pointer type-safe. The return type should also match. Delegate covariance provides some flexibility with the signature. You assign function pointers to delegates based on signature, not type. Regardless of the object or type that binds the function, it is assignable to a delegate of the same signature.
Functions called with a delegate are given the security context of the caller, which prevents a delegate from performing a task not available to a lower-privilege caller. Delegates can be initialized with pointers to functions that are implemented anywhere. The only limitation is the signature. Callers need to be careful when invoking delegates containing function pointers to unknown sources, where there could be unexpected implementation. Use code access security to protect delegates.
Delegates are useful as general function pointers, callbacks, events, and threads. As a general function pointer, a delegate can be a method parameter, function return, class member, or local variable. Callbacks are valuable in many scenarios, including promoting peer-to-peer relationships, in which objects swap function pointers to send bilateral messages. Events support a publisher/subscriber model. The publisher notifies subscribers of events, whereas the subscriber registers functions to be called when the event occurs. Finally, a delegate is a path of execution for a thread, which is an asynchronous function call.
-
Archives
- February 2009 (1)
- November 2008 (6)
- October 2008 (4)
- September 2008 (13)
- August 2008 (11)
- July 2008 (29)
- June 2008 (19)
- May 2008 (8)
-
Categories
-
RSS
Entries RSS
Comments RSS

