Sunday, January 29, 2012

Anonymous methods in C#


An anonymous method is just a method that has no name. Anonymous methods are most frequently used to pass a code block as a delegate parameter.

Before C# 2.0, the only way to declare a delegate was to use named methods as shown in the example below

// Create the delegate
public delegate void Display(string message);

// Create the method
public static void DisplayOnConsole(string myMessage)
{
    Console.WriteLine(myMessage);
}

public static void Main(string[] args)
{
    // Here, the delegate is instantiated with the
    // method which should be invoked.
    Display myDisplay = new Display(DisplayOnConsole);

    // Invoke
    myDisplay("Hello World!");
}

Then C# 2.0 introduced the concept of anonymous methods.

// Creation of delegate with an anonymous method
Display newDisplay = delegate(string msg)
{
    // Anonymous method body
    Console.WriteLine(msg);
};

// Invoke
newDisplay("Hello World using Anonymous methods.");

The difference here is quite apparent. Creation of a new method to act as a handler is not required; the delegate itself specifies what should be done when invoked. Anonymous methods reduce the coding overhead in instantiating delegates because you do not have to create a separate method. Specifying a code bolck instead of a delegate can be useful in situations where creation another method might seem an unnecessary overhead.

Some other points to remember:
  • There cannot be any jump statements like goto, break or continue inside the code block if the target is outside the block and vice versa.
  • The scope of parameters of an anonymous method is the anonymous code block.
  • No unsafe code can be used within the anonymous code block.
  • The local variables and parameters whose scope contains an anonymous method declaration are called outer variables of the anonymous method. 

In the following code the variable x is an outer variable.

int x = 0;
Display newDisplay = delegate(string msg)
{
    Console.WriteLine(msg + x);
};
  • An anonymous method cannot access the ref or out variables of an outer scope.
C# 3.0 introduces lambda expressions which are pretty much similar to anonymous methods but more expressive and concise. Applications written using .NET Framework version 3.5 and higher should make use of lambda expressions instead of anonymous methods. I will discuss lambda expressions in detail after I start with LINQ (Language Integrated Query) in my following posts.

1 comment:

  1. When a delegate is created, the outer variable is said to be captured. Normally, the local variables life time is limited to execution of the block or statement with which it is associated. However, the life time of a captured outer variable is extended at least until the delegate referring to the anonymous method becomes eligible for garbage collection. This means that a captured outer variable remains alive as long as its capturing method is part of the delegate, even if the variable would have normally gone out of scope.

    .net training

    ReplyDelete