Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

October 16, 2009

Lambda Expressions: Execution

Filed under: C#,Lambda Expressions,VB.NET @ 3:26 pm

Lambda expressions can be assigned to a delegate variable. The lambda expression is then executed when the delegate is called.

[To begin with an overview of lambda expressions, start here.]

In the following example, a lambda expression is assigned to a variable (f).

In C#:

Func<int,string> f = x => (x + x).ToString();
Debug.WriteLine(f(5));
Debug.WriteLine(f(10));

In VB:

Dim f = Function(x as Integer) (x + x).ToString()
Debug.WriteLine(f(5))
Debug.WriteLine(f(10))

The lambda expression in this example is a Func<int, string> [Func(Of Integer, String) in VB] meaning it takes one integer input parameter and returns a string. The lambda expression simply takes the input value, adds it to itself, and returns the result as a string.

[For more information on Func delegates, see this post.]

When the expression is defined, it is not executed. It is not executed until it is called.

The first Debug.WriteLine statement calls the lambda expression, passing in a 5. The result displays "10" in the debug window.

The second Debug.WriteLine statement calls the lambda expression again, passing in a 10. The result displays "20" in the debug window.

Lambda expressions are executed when they are called, not when they are constructed. This is important to consider, especially when the lambda expression contains local variables.

Local variables used in a lambda expression are “captured” or “lifted”. The variable value used is the value at execution time. The variable lifetime extends to the lifetime of the delegate.

The following code updates the original example to use a local variable.

In C#:

int y = 0;
Func<int,string> f = x => (x + y).ToString();
y = 10;
Debug.WriteLine(f(5));

In VB:

Dim y As Integer = 0
Dim f = Function(x) (x + y).ToString()
y = 10
Debug.WriteLine(f(5))

The lambda expression in this example takes the input value, adds it to the current value of the local variable (y), and returns the result as a string.

The Debug.WriteLine statement in this example calls the lambda expression, passing in a 5.  At the point of executing the Debug statement, y is 10, so the result displays "15" in the debug window.

For another example of using lambda expressions with local variables, see this post.

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs