Methods in C# - Anonymous Methods
(Page 3 of 4 )
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 toExpression<T>
To write an anonymous method, you include thedelegatekeyword 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.
Next: try Statements and Exceptions >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|