Anonymous Function Expressions

That’s a good start, but the need to create a method even for the tiniest of methods to be used or passed as a delegate is quite cumbersome, too. Why do we need to create a whole Add method with the appropriate signature if we just want to express “add two numbers”? Can’t we just somehow declare the method “inline” and have the compiler take care of creating a method under the hood that’s referred to by the delegate? C# 2.0 introduced such a feature, called anonymous function expressions:

static void Main() {    BinOp add = delegate (int a, int b) { return a + b; };    int three = add(1, 2); // calls the anonymous method through the delegate}

In the preceding code, we’re declaring an ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.