C# Lambda Capturing Outer Variables
In this chapter you will learn:
- What are Lambda Capturing Outer Variables
- Example for Lambda Capturing Outer Variables
- Captured variables evaluation
- Update captured variables
- Lifetime of Captured variables
Description
A lambda expression can reference the local variables and parameters of the method in which it's defined (outer variables).
Outer variables referenced by a lambda expression are called captured variables. A lambda expression that captures variables is called a closure.
Example
For example:
using System;// w ww. ja va 2 s . com
public class MainClass{
public static void Main(String[] argv){
int factor = 2;
Func<int, int> multiplier = n => n * factor;
System.Console.WriteLine (multiplier (3)); // 6
}
}
The code above generates the following result.
Captured variables evaluation
Captured variables are evaluated when the delegate is actually invoked, not when the variables were captured:
using System;/*from w w w .j ava 2 s. c o m*/
public class MainClass{
public static void Main(String[] argv){
int factor = 2;
Func<int, int> multiplier = n => n * factor;
factor = 10;
System.Console.WriteLine (multiplier (3)); // 30
}
}
The code above generates the following result.
Update captured variables
Lambda expressions can themselves update captured variables:
using System;/*from www . j a va 2 s . c om*/
public class MainClass{
public static void Main(String[] argv){
int seed = 0;
Func<int> natural = () => seed++;
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 1
Console.WriteLine (seed); // 2
}
}
The code above generates the following result.
Lifetime of Captured variables
Captured variables have their lifetimes extended to that of the delegate.
using System;//ww w . jav a 2 s. c o m
public class MainClass{
static Func<int> Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
static void Main()
{
Func<int> natural = Natural();
System.Console.WriteLine (natural()); // 0
System.Console.WriteLine (natural()); // 1
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: