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 {

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)
del("Hello, World!");  


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

MSDN has a comprehensive article on anonymous methods.  Check it out at

Comments (0)

Skip to main content