Anonymous Methods in C# 2.0

Delegates are defined as "a reference type that can be used to encapsulate a method with a specific signature"

The use of delegates is involved in event handlers, callbacks, asynchronous calls, and multithreading, among other uses.

Before C# 2.0, the only way to use delegates was to use named methods. In some cases, this results in the forced creation of classes only for use with delegates. In some cases, these classes and methods are never even invoked directly.

C# 2.0 offers an elegant solution for these methods described above. Anonymous methods allow the declaration of inline methods without having to define a named method.

This is very useful, especially in cases where the delegated function requires short and simple code. Anonymous methods can be used anywhere where a delegate type is expected.

What are Anonymous Methods in C# 2.0?

Anonymous Method declarations consist of the keyword delegate, an optional parameter list, and a statement list enclosed in parenthesis

Event Handler (without using anonymous methods)

btnSave.Click += new EventHandler(btnSave_Click);
void AddClick(object sender, EventArgs e)
{
    SaveChanges();
    lblStatus.Text = "Your changes have been saved";
}

Event Handler (using anonymous methods)

btnSave.Click += delegate
{
    SaveChanges();
    lblStatus.Text = "Your changes have been saved";
};

Event Handler using Anonymous Methods with a parameter list

btnSave.Click += delegate(object sender, EventArgs e)
{
    MessageBox.Show(((Button)sender).Text);
    SaveChanges();
    MessageBox.Show("Your changes have been saved");
};

Anonymous methods can be specified with parameters enclosed in parenthesis, or without parameters, with empty parenthesis. When parameters are specified, the signature of the anonymous method must match the signature of the delegate. When the delegate has no parameters, empty parenthesis is specified in the anonymous method declaration. When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any signature.

Note that method attributes cannot be applied to Anonymous methods. Also, anonymous methods can be added to the invocation list for delegates but can be deleted from the invocation list only if they have been saved to delegates.

An advantage offered by the use of anonymous methods is that they allow access to the local state of the containing function member.

Conclusion

Anonymous methods offer a simple and elegant solution in many situations. In the next version of C#, (C# 3.0), anonymous methods are evolved into Lambda Expressions used in Language Integrated Query (Linq).

Disclaimer

This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof


Similar Articles