C# closure example


/ Published in: C#
Save to your folder(s)

Shows an example of what a closure is.

Result: Counter=1 Counter= 2


Copy this code and paste it in your HTML
  1. public class Test {
  2.  
  3. static void Main() {
  4. Action action = Test.CreateAction();
  5. action();
  6. action();
  7. Console.ReadLine();
  8. }
  9.  
  10. public static Action CreateAction() {
  11. int counter = 0;
  12. return delegate {
  13. // Yes, it could be done in one statement;
  14. // but it is clearer like this.
  15. counter++;
  16. Console.WriteLine("counter={0}", counter);
  17. };
  18. }
  19. }

URL: http://csharpindepth.com/articles/chapter5/closures.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.