O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required