Return to Snippet

Revision: 64210
at July 15, 2013 17:39 by venu1729


Initial Code
public class Test {

        static void Main() {
			Action action = Test.CreateAction();
            action();
            action();
            Console.ReadLine();
        }
		
        public static Action CreateAction() {
            int counter = 0;
            return delegate {
                // Yes, it could be done in one statement; 
                // but it is clearer like this.
                counter++;
                Console.WriteLine("counter={0}", counter);
            };
        }
    }

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

Initial Description
Shows an example of what a closure is.   

Result: Counter=1    Counter= 2

Initial Title
C# closure example

Initial Tags
c#

Initial Language
C#