Anonymous Methods in C# 2.0

Introduction

C# 2.0 (and .NET in general) introduces the anonymous method. An anonymous method can be used anywhere a delegate is used and is defined inline, without a method name, with optional parameters and a method body.To use anonymous methods, you need to know what a delegate is.
Anonymous methods are a condensed way to declare and use delegates.delegates are the next evolution of raw function pointers. A delegate is a class that encapsulates the pointer; implicitly, delegates in .NET are multicast delegates. To be a multicast delegate simply means that the "one function to one pointer" limitation is gone, because the multicast delegate class contains a list of pointers


Anonymous Methods Are Inline Delegates

Generally, when we're using delegates, we have a method. That method's signature matches the signature prescribed by a delegate and can be used to initialize a delegate instance. Anonymous methods are used to condense the method and initialization of the delegate into a single location.



private void Form1_Load(object sender, EventArgs e)
{
button1.Click += delegate
{
Debug.WriteLine("button1 clicked");
}




Anonymous methods can be used wherever delegates are expected. Anonymous methods can use ref and out arguments, but cannot reference ref or out parameters of an outer scope. Anonymous methods can't use unsafe code, and anonymous methods can't use goto, break, or continue in such a way that the branch behavior causes a branch outside of the anonymous method's code block

Are anonymous methods a good thing? The marketing material says that anonymous methods are good because they reduce code overhead caused by instantiating delegates and reducing separate methods. But the marketing material also says that anonymous methods increase usability and maintainability.

EXAMPLE:
Does this code look easily maintainable?


private void Form1_Load(object sender, EventArgs e)
{
BindClick(delegate { Debug.WriteLine("button1 click"); });
}

private void BindClick(EventHandler handler)
{
button1.Click += handler;
}



In this sample, we're passing a delegate to a method by passing the delegate as an anonymous method. Just keeping the order and number of the parentheses, semicolons, and brackets straight is a pain in the neck.

The cited classic example is that anonymous methods can reduce the overhead of creating delegates and methods just for kicking off threads (which use delegates). This is true, but threads are used infrequently and are already difficult enough to use correctly; I wonder how prudent it is to make the code more esoteric rather than less.

Summary


Anonymous methods are examples of methods without names that can be defined and used anywhere a delegate can be used. Delegates are wrappers for event handlers. How practical and generally useful anonymous methods are remains to be seen.