Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created February 1, 2015 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/62c624b56a7dcd25ea15 to your computer and use it in GitHub Desktop.
Save ufcpp/62c624b56a7dcd25ea15 to your computer and use it in GitHub Desktop.
Local variable captured by lambda
using System;
class Program
{
static void Main()
{
var f = X();
Console.WriteLine(f(1)); // 1 (value += 1)
Console.WriteLine(f(2)); // 3 (value += 2)
Console.WriteLine(f(3)); // 6 (value += 3)
}
static Func<int, int> X()
{
int value = 0; // ローカルな変数に見えて…
return x => value += x; // こいつのせいで外から書き替えられる
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment