Musings
Public · Protected · Private
Closures in c# .NET
-
2012-08-07 21:03Check these two cases private void button4_Click(object sender, EventArgs e) { Func<string, string> GreetHellow = delegate(string var1) { return " Hellow 2 " + var1; }; Func<string, string> GreetHi = var1 => " hi 2 " + var1; Console.WriteLine(GreetHellow("Janaganamana")); Console.WriteLine(GreetHi("Janaganamana")); } OR Func<string, string> GreetHellow = delegate(string var1) { return " Hellow 2 " + var1; }; Func<string, string> GreetHi = var1 => " hi 2 " + var1; private void button4_Click(object sender, EventArgs e) { Console.WriteLine(GreetHellow("Janaganamana")); Console.WriteLine(GreetHi("Janaganamana")); } Both give following output //Hellow 2 Janaganamana //hi 2 Janaganamana
-
2012-08-07 21:10Now check a similar case private void button3_Click(object sender, EventArgs e) { var inc = GetAFunc(); Console.WriteLine(inc(5)); globalint = 10; Console.WriteLine(inc(5)); } static int globalint = 0; public static Func<int, int> GetAFunc() { int x = 10; int y = 10; var myVar = x + y + globalint; Func<int, int> inc = delegate(int var1) { myVar = myVar + 1; return var1 + myVar; }; return inc; } Notice the following lines are visited only once ( once to get func pointer) output is 26 27 so "globalint = 10;" is not reflected. Also notice "myVar " is a live variable that keeps latest value (myVar = myVar +1 " keeps incrementing.
-
2012-08-07 21:28It may look little ODD (but is Fair - CLOSURE) while breakpoint dont stop @ "var myVar = x + y + globalint; " It stops only once while fetching func pointer. Notice myVar works within the scope (CLOSURE)of this button click event (it incremented within this scope.)
This blog is frozen. No new comments or edits allowed.