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.

C#:
  1. foreach(DataRow g in groups.Rows)
  2. {
  3.     DataRow tmp = g; // [1]
  4.     Button b = new Button(g[“name”].ToString());
  5.  
  6.     b.Clicked += delegate {
  7.         Console.WriteLine(“I’m button {0}, id {1}”,
  8.             tmp[“name”], tmp[“id”]);
  9.     };
  10.     hbuttonbox.PackStart( b );
  11.     b.Show();
  12. }

More info at http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx and google…
Thanks goes to Miguel (#mono @ irc.gimp.net)

Brak powiązanych wpisów

Leave a Reply