blog vipa
mój dzień to 3 filiżanki kawy

blog vipa

Anonymous delegates in C#

Listopad 17th, 2008 . by vip

Beware 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.
[csharp]
foreach(DataRow g in groups.Rows)
{
DataRow tmp = g; // [1]
Button b = new Button(g[„name”].ToString());

b.Clicked += delegate {
Console.WriteLine(„I’m button {0}, id {1}”,
tmp[„name”], tmp[„id”]);
};
hbuttonbox.PackStart( b );
b.Show();
}
[/csharp]
More info at http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx and google…
Thanks goes to Miguel (#mono @ irc.gimp.net)

Leave a Reply