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

Other versions are also available for the following:
C# Programming Guide
Anonymous Methods (C# Programming Guide)

In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:

C#
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };

or

C#
// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };

By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.

C#
void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}

The scope of the parameters of an anonymous method is the anonymous-method-block.

It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.

The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method. For example, in the following code segment, n is an outer variable:

C#
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };

Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.

An anonymous method cannot access the ref or out parameters of an outer scope.

No unsafe code can be accessed within the anonymous-method-block.

The following example demonstrates the two ways of instantiating a delegate:

  • Associating the delegate with an anonymous method.

  • Associating the delegate with a named method (DoWork).

In each case, a message is displayed when the delegate is invoked.

C#
// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork":
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call:
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate:
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}

The delegate using the anonymous method is called.

The delegate using the named method is called.

Community Content   What is Community Content?
Add new content RSS  Annotations
Consequences Of Anonymous Delegates      Steve Butler MSFT   |   Edit   |   Show History

Raymond Chen posted an excellent series of blog articles on anonymous delegates. Most poinent was the consequences of passing in variables external to the delegate declaration.

The implementation of anonymous methods in C# and its consequences (part 3)

http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx

Anonymous methods as Lambda expressions.      Mujahid Khaleel   |   Edit   |   Show History

In .net framework 3, along with LINQ, microsoft introduced lambda expressions. Lambda expressions are short hand for anonymous methods. => is called lambda operator.

Read more here... http://www.mujahiddev.com/2009/01/lambda-expressions-c.html

How does one remove the anonymous delegate?      AcousticGuitar   |   Edit   |   Show History
The example works great for adding the delegate, but how does one remove that particular delgate?
To remove the anonymous delegate      atlantsoft   |   Edit   |   Show History
var myDelegate = delegate(){Console.WriteLine("I did it!");};
MyEvent += myDelegate;
// .... later
MyEvent -= myDelegate;
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker