About Me

Hyderabad, Andhra Pradesh, India

Tuesday, June 28, 2011

Delegates Overview

Delegates have the following properties:

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contravariance
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

Delegates are fun. If you've been programming for any length of time, you've been introduced to the concept of delegates as function pointers.

As a quick review, pointers are used to store the address of a thing. By changing the address contained in a pointer, the same pointer can reference multiple things during the course of execution of a program.

Thus, a pointer named "stackTop" can point to an infinite number of things as they are pushed and popped from a stack implementation.

We are most familiar with pointers pointing to pieces of information. However, since pointers just store addresses under the covers, they can point to other program data as well.

In particular a pointer can store the location of a function entry point and a programmer can use the pointer to instruct a computer to execute at the location stored in the pointer.

Typically, the role of telling the computer how to hop around is relegated to the compiler and all the jumps are determined before the program starts running. However, it is sometimes not possible to know all the jumps when a program is compiled and the jumps need to be determined by a program as it executes.

This is where we typically use function pointers.

No comments:

Post a Comment