Skip to content

Instantly share code, notes, and snippets.

@tkellogg
Created June 25, 2012 04:19
Show Gist options
  • Save tkellogg/2986491 to your computer and use it in GitHub Desktop.
Save tkellogg/2986491 to your computer and use it in GitHub Desktop.
"The anatomy of closures" blog post
class Anon1
{
private int second;
// constructor
public Anon1(int second)
{
this.second = second;
}
public int Apply(int x)
{
return second * x;
}
}
class EvilIncarnate
{
// hold the reference forever
private static PandorasBox boxOfSecrets;
public int[] CalculateDeviations(int ages)
{
var dataTable = // query the database for average age
boxOfSecrets = new PandorasBox();
return boxOfSecrets.Map(ages, x => ((int)dataTable[0]) * x);
}
}
public int[] Map(int[] original, Func<int, int> mapper)
{
var result = new int[original.Length];
for (int i = 0; i < original.Length; i++)
result[i] = mapper(original[i]);
return result;
}
var numbers = new[] { 1, 5, 3, 17 };
var squares = Map(numbers, x => x * x);
var halves = Map(numbers, x => x / 2);
var second = DateTime.Now.Second;
var aritrary = Map(numbers, x => second * x);
class PandorasBox
{
private Func<int, int> captor;
public int[] Map(int[] numbers, Func<int, int> functor)
{
captor = functor;
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment