Posted By

venu1729 on 07/15/13


Tagged

c#


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

danfinrud55
Priestd09


C# closure example


 / Published in: C#
 

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

Shows an example of what a closure is.

Result: Counter=1 Counter= 2

  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. }

Report this snippet  

You need to login to post a comment.