The beauty of anonymous methods (aka lambda expressions)

Anonymous methods are a new feature in .Net 2.0. One who is unfamiliar with anonymous methods may not immediately see the usefulness of this construct. It would seem as if anonymous methods are no more powerful than named methods, but this is not true. Take this code for example:

delegate void voidDelegate();

void SetEvent(InputEvent ie)
        {
            Invoke(new voidDelegate(delegate() { 

                eventText.Text = ie.ToString(); 

            }));
        }

This is a function that sets the text of a form element. The problem with interacting with anything in the user interface, however, is that it must be done in the form’s thread. If you are in the context of another thread, you cannot set any properties of user interface elements (since this would not be threadsafe, and is enforced by the .Net runtime). The workaround for this, is to use the Invoke method, which does a synchronous invokation in the context of the forms thread. The difficulty with using Invoke is that it must be done with delegates. Normally, this would mean defining a new function to do the work or playing around with parameter lists to re-invoke the function with the proper context and parameters. However, with anonymous methods this can be done much more easily.

Comments

  1. Chris says:

    The idea of invoking a method anonymously has been around since Java 1.2, where you could insert an anonymous class that served a particular interface. .NET takes this a step further and provides an anonymous method as an individual level of abstraction.

    While .NET is using what could basically be called anonymous methods, the MS syntax for (Ed. the entry point to) this is a delegate, for some reason or other.

    The really fascinating/difficult part of both anonymous classes and anonymous delegates, however, is how they deal with variables. In order for the delegate in this example to work, it must have access to eventText, which is probably both private and outside of the delegate! .NET and Java both have special rules for scope in anonymous classes/methods; they allow them to access things directly outside of them.

    (more info: http://www.devx.com/Intel/Article/21147)

  2. Tim says:

    Actually, you’re incorrect. The idea of invoking a method anonymously has been around much longer than Java has been around. Lambda expressions were one of the early formalizations of language design, and are present in languages such as ML, which was developed in 1974.

    Delegates in C# are not the same as anonymous methods. The original use of delegates was as a way to treat named methods as first-order values in the language (much like is available in functional languages like SML or Lisp). Using the delegate keyword as a way to implement anonymous methods as first-order values is a logical extension of the original purpose of the keyword.

    In classic scoping rules (e.g. SML), it’s unsurprising for lambda expressions to simply represent a nested scope. Practical implementation of variable scope in anonymous method is often done through the use of a static link in the activation record (except in languages with dyanamic scoping)

  3. Chris says:

    I didn’t claim that Java invented the anonymous method; it’s simply one of the first widespread instances and I didn’t intend for it to seem like Java invented anonymous entities. My point was simply that while they are a new innovation in .Net, they’re not new new. Sorry about that.

    Whether using it as an anonymous method or in another fashion, it would be incorrect to claim that what was implemented above is not a delegate. You’re right that delegates are separate from anonymous methods; classes can also implement such methods, but I would call them anonymous classes because strictly speaking they’re not anonymous methods.

    Anyways, you’re right.

  1. [...] Gas discusses this when he referred to the concept of lambda calculus and functions as first order values. (You may be more familiar with Joel on Software’s example.) The idea here is that, instead of working primarily with objects, you work with functions. Inherently, a function knows what to do with its input; unlike objects, functions are defined by the output they produce for a particular input. [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>