Section 1.6. Simplify Your Code with Anonymous Methods


1.6. Simplify Your Code with Anonymous Methods

Anonymous methods allow you to define method blocks inline. In general, you can use anonymous methods anywhere you can use a delegate. This can greatly simplify registering event handlers.

1.6.1. 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.


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

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.

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";  };

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.

1.6.2. What about . . .

...using anonymous methods in my own code?

No problem. Not only can you use anonymous methods when you initialize delegates, but also you can pass a block of code anywhere you might otherwise use a delegate.

...what happens if I reference local variables in my anonymous block?

Good question. This can cause quite a bit of confusion and is a natural trap to fall into, especially if you don't fully understand the consequences. C# allows local variables to be captured in the scope of the anonymous code block, and then they are accessed when the code block is executed. This can create some odd side effects, such as keeping objects around after they might otherwise have been collected.

...what about removing the handler for an event that I added with an anonymous delegate; how do I do that?

If you add an event handler with an anonymous delegate, you cannot remove it; therefore, I strongly recommend that you use anonymous delegates only for event handlers you expect to keep permanently attached.

You can use anonymous delegates for other requirements, such as implementing a List.Find method that takes, for example, a delegate describing the search criteria.

1.6.3. Where can I learn more?

On the MSDN web site, you'll find a good article touching on anonymous methods. Written by Juval Lowy, the article is titled "Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes." Also, visit O'Reilly's ONDotnet.com site at http://www.ondotnet.com/pub/a/dotnet/2004/04/05/csharpwhidbeypt1.html.



Visual C# 2005(c) A Developer's Notebook
Visual C# 2005: A Developers Notebook
ISBN: 059600799X
EAN: 2147483647
Year: 2006
Pages: 95
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net