Welcome to MSDN Blogs Sign in | Join | Help

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/

Published Wednesday, December 14, 2005 5:32 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker