Send mail to the author(s) E-mail

# Tuesday, 25 August 2015

What is a class?

Holds state (properties or fields)
Has behaviour (methods)

What is a closure?

“A closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created ie it can still use the local variables of the method which created it, even after that method has finished executing”

Closing over something that may go out of scope

// Action is a delegate which doesn't return a value Action action = CreateAction(); //Here we can see that the action returned by CreateAction still has access to the counter variable, //and can indeed increment it, even though CreateAction itself has finished. action(); action(); } static Action CreateAction() { int counter = 0; Action a = delegate { counter++; Console.WriteLine("counter={0}", counter); }; return a; }


A Function:

// setting up state of function Func<int, int> fn2 = GetMultiplier(2); //var fn3 = GetMultiplier(3); Console.WriteLine(fn2(2)); //outputs 4 Console.WriteLine(fn2(3)); //outputs 6 //Console.WriteLine(fn3(2)); //outputs 6 //Console.WriteLine(fn3(3)); //outputs 9 } static Func<int, int> GetMultiplier(int a) { int multiplier = a; Func<int, int> multiplierFunction = delegate(int b) { return multiplier * b; }; return multiplierFunction; }

and again:

Action a = GiveMeAction(); a(); // i = 1 a(); // i = 2 a(); } static Action GiveMeAction() { int i = 0; Action a = delegate { i++; }; // Returning a method/function which captures the i scope (closure) return a; }


// A delegate that accepts a string and returns a string Func<string, string> myFunc = delegate (string var1) { return "some value"; }; string myVar = myFunc("something"); Console.Out.WriteLine($"myVar is {myVar}");

When to use closures?

LINQ is built using clousures

  • Simplify interfaces
  • Delayed execution
| | #