Recent site activity

C# - C Sharp‎ > ‎

Anonymous Methods


Anonymous methods are a C# 2.0 feature that has been subsumed by C# 3.0 lambda expressions. An anonymous method is like a lambda expression, but it lacks the following features:
  • Implicitly typed parameters
  • Expression syntax (an anonymous method must always be a statement block)
  • The ability to compile to an expression tree, by assigning to Expression<T>

To write an anonymous method, you include the delegate keyword followed by a parameter declaration and then a method body. For example:delegate int Transformer (int i);
class Test
{
     static void Main( )
     {
         Transformer square = delegate (int x) {return x * x;};
         Console.WriteLine (square(3)); // 9
     }
}

The following line Transformer square = delegate (int x) {return x * x;} is semantically equivalent to the following lambda expression Transformer square = (int x) => {return x * x;}; Or simply Transformer square = x => x * x;
Anonymous methods capture outer variables in the same way lambda expressions do.