Anonymous delegates in C#
listopad 17th, 2008 . by vipBeware of anonymous delegates in C#! You’ve to instanize new variable to have them in own delegate instances. If not, you’ll get the last value of variable in loop.
Short snippet for Gtk#. It creates dynamic buttons and actions from DataTable (e.g. database). Pay attention to line // [1], when “variable capturing” is used.
C#:
-
foreach(DataRow g in groups.Rows)
-
{
-
DataRow tmp = g; // [1]
-
-
b.Clicked += delegate {
-
Console.WriteLine(“I’m button {0}, id {1}”,
-
tmp[“name”], tmp[“id”]);
-
};
-
hbuttonbox.PackStart( b );
-
b.Show();
-
}
More info at http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx and google…
Thanks goes to Miguel (#mono @ irc.gimp.net)

