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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.