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.
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 );
More info at and google…
Thanks goes to Miguel (#mono @

Leave a Reply