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.