Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
Delegates
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:

Want more? Here are some additional resources on this topic:

C# Programming Guide
Delegates (C# Programming Guide)

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:

C#
public delegate int PerformCalculation(int x, int y);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.

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.

In This Section

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.11 Delegates

  • 4.2.6 Delegate types

  • 7.5.5.2 Delegate invocations

  • 15 Delegates

See Also

Community Content   What is Community Content?
Add new content RSS  Annotations
typo      pratyak ... Thomas Lee   |   Edit   |  
2nd para, 2nd line- read as 'This makes it possible to..'
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker