Wednesday, December 17, 2008

Understanding closures a bit more

Here is an 18 line C# program that gives some insights into closures. Try to anticipate what it would print. For those that haven't seen lambda expressions before, it might give hints as to how they can be used too.

using System;
namespace ClosureTest {
 class Program {
  public delegate int TestDelegate(int i);
  
  public static void Main(string[] args) {
   var add2 = Adder(2);
   Console.WriteLine(add2(8).ToString());
   Console.WriteLine(add2(15).ToString());
   Console.WriteLine(add2(add2(12)).ToString());
   Console.ReadLine();
  }
  
  public static TestDelegate Adder(int i) {
   return x => x + i;
  }
 }
}

No comments: