New Features in C# 2.0—Anonymous Methods: How do I do that?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

How do I do that?

To see how you can use an anonymous method, follow these steps:

1. Open a new Windows application in Visual Studio .NET 2005 and call it AnonymousMethods.

2. Drag two controls onto the default form: a label and a button. Don’t bother renaming them.

3. Double-click the button. You will be taken to the code page, where you will enter the following code:

private void button1_Click(object sender, EventArgs e)
{
  label1.Text = "Goodbye";
}

4. Run and test the application. Clicking the button changes the label text to Goodbye.

Great. No problem. But there is a bit of overhead here. You must register the delegate (Visual Studio 2005 did this for you), and you must write an entire method to handle the button click. Anonymous methods help simplify these tasks.

To see how this works, click the Show All Files button, as shown in Figure 1-1.


Image:VisualCSDevNbookfig1-1.jpg
Figure 1-1. Show All Files button


Open Form1.Designer.cs and navigate to the delegate for button1.Click:

this.button1.Click += new System.EventHandler(this.button1_Click);

You can’t replace this code without confusing the designer, but we will eliminate this line by returning to the form and clicking the lightning bolt in the Properties window, to go to the event handlers. Remove the event handler for the Click event.

If you return to Form1.Designer.cs you’ll find that the button1.Click event handler is not registered!

Next, open Form1.cs and add the following line to the constructor, after the call to InitializeComponent( ):

this.button1.Click += delegate { label1.Text = "Goodbye"; };


Anonymous methods allow you to pass a block of code as a parameter.


Now you are ready to delete (or comment out) the event handler method:

// private void button1_Click(object sender, EventArgs e)
// {
// label1.Text = "Goodbye";
// } 

Run the application. It should work exactly as it did originally.

Instead of registering the delegate which then invokes the method, the code for the delegate is placed inline in an anonymous method: that is, an inline, unnamed block of code.


Previous_Page_.gif Next_Page_.gif


Personal tools