Anonymous Methods
Lambda expressions were added to the language in C# 3.0. Before that, there was a tool called an anonymous method. Anonymous methods still exist, and can be used, though they’ve fallen out of common use because lambda expressions are usually a superior option.
Suppose we have a variable called action
, whose type is the delegate type Action
.
We want it to store a method with no parameters and a void
return type.
We can assign it a normal, named method like this:
Action action = DoSomething;
action.Invoke();
void DoSomething()
{
Console.WriteLine("Hello, World!");
}
Or, if we wanted to use a lambda instead of a named method, we could do this:
Action action = () => Console.WriteLine("Hello, World!");
action.Invoke();
The anonymous method version of this used the delegate
keyword, and looks like this:
Action action = delegate { Console.WriteLine("Hello, World!"); };
action.Invoke();
Contrasted with a lambda (and a named method), anonymous methods must have a block body.
You can optionally include the parentheses if you want:
Action action = delegate() { Console.WriteLine("Hello, World!"); };
action.Invoke();
If you have parameters, the parentheses are mandatory, and you add them like this:
Action<string> action = delegate(string text) { Console.WriteLine(text); };
action.Invoke("Hello, World!");
One nice extra feature of anonymous methods is that in situations where a parameter is expected but goes unused, you can simply leave it off:
Action<string> action = delegate { Console.WriteLine("Hello, World!"); }
action.Invoke("This text is ignored.");
By comparison to lambda expressions, you get none of the little features that make lambdas short and easy to read. Because of that, you should usually prefer a lambda to an anonymous method.
Having said that (and the reason this article exists), there is one scenario where I still sometimes see anonymous methods used: giving events a non-null value. The book describes doing this with a lambda:
public event Action SomethingHappened = () => {};
But the following anonymous method version is not uncommon either:
public event Action SomethingHappened = delegate { };
Either version works fine, and you’ll see both (as well as the version that allows the event to be null, and using Action?
instead of Action
).