Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

delegate (C# Reference)

The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type:

public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);

A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.

Delegates are the basis for Events.

A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods.

The delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters. For more information on the degree of variance that is allowed in the method signature, see Covariance and Contravariance in Delegates. For use with anonymous methods, the delegate and the code to be associated with it are declared together. Both ways of instantiating delegates are discussed in this section.

// Declare delegate -- defines required signature: 
delegate double MathAction(double num);

class DelegateTest
    // Regular method that matches signature: 
    static double Double(double input)
        return input * 2;

    static void Main()
        // Instantiate delegate with named method:
        MathAction ma = Double;

        // Invoke delegate ma: 
        double multByTwo = ma(4.5);

        // Instantiate delegate with anonymous method:
        MathAction ma2 = delegate(double input)
            return input * input;

        double square = ma2(5);

        // Instantiate delegate with lambda expression
        MathAction ma3 = s => s * s * s;
        double cube = ma3(4.375);


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

  • 1.11 Delegates

  • 15 Delegates

© 2016 Microsoft