Skip to Main Content
Professional Visual Studio® 2008
book

Professional Visual Studio® 2008

by Nick Randolph, David Gardner
July 2008
Intermediate to advanced content levelIntermediate to advanced
1026 pages
27h 59m
English
Wrox
Content preview from Professional Visual Studio® 2008

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional Visual Studio® 2010

Professional Visual Studio® 2010

Nick Randolph, David Gardner, Michael Minutillo, Chris Anderson

Publisher Resources

ISBN: 9780470229880Purchase book