12.5. Lambda Expressions
Over successive versions of the .NET Framework, the syntax with which you can define and reference reusable functions has evolved. In the early versions, you had to explicitly declare a delegate and then create an instance of it in order to obtain a reference to a function. In version 2.0 of the .NET Framework, C# shipped with a new feature called anonymous methods, whereby you could declare a multiple-line reusable function within a method. Lambda expressions in their simplest form are just a reduced notation for anonymous methods. However, lambda expressions can also be specified as expression trees. This means that you can combine, manipulate, and extend them dynamically before invoking them.
To begin with, let's examine the following simple lambda function, which takes an input parameter, x, increments it, and returns the new value. When the function is executed with an input value of 5, the return value assigned to the variable y will be 6.
VB.NET
Dim fn As Func(Of Integer, Integer) = Function(x) x + 1 Dim y As Integer = fn(5)
C#
Func<int, int> fn = x => x + 1; int y = fn(5);
You can see that in both languages the type of fn has been explicitly declared. Func is a generic delegate that is defined within the framework and has five overloads with a varying number of input parameters and a single return value. In this case there is a single input parameter, but because both input and return values are generic, there are two generic parameters. From the ...
Get Professional Visual Studio® 2008 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.