SYSK 28: Do you know about ‘Anonymous Methods’? If not, read on…


Have you ever created a delegate that has just a couple of lines of code?  If yes, in .NET 2.0 you could’ve put that code right “in-line” as demonstrated below:


class MyForm : Form
{
   ListBox listBox;
   TextBox textBox;
   Button addButton;


   public MyForm() {
      listBox = new ListBox(…);
      textBox = new TextBox(…);
      addButton = new Button(…);
      addButton.Click += delegate {
         listBox.Items.Add(textBox.Text);
      };
   }
}


You can pass an anonymous method into any method that accepts the appropriate delegate type as a parameter.


To pass a parameter to an anonymous delegate, use the following syntax:
SomeDelegate del = delegate(string arg)
{
MessageBox.Show(arg);
};
del(“Hello, World!”);  


or


button.Click += delegate(object sender, EventArgs e) { MessageBox.Show(((Button)sender).Text); };


MSDN has a comprehensive article on anonymous methods.  Check it out at http://msdn.microsoft.com/msdnmag/issues/04/05/C20/


Comments (0)