Anonymous Methods in C# 2.0
Anonymous methods is a new feature in C# 2.0 that lets you define an anonymous (that is, nameless) method called by a delegate. Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); };
The anonymous method is defined in-line and not as a member method of any class.
Anonymous methods can be used anywhere that a delegate type is expected. You can pass an anonymous method into any method that accepts the appropriate delegate type as a parameter. A concrete and useful example for passing an anonymous method as a parameter is launching a new thread without explicitly defining a ThreadStart delegate or a thread method:
void StartThread(){
System.Threading.Thread t1 = new System.Threading.Thread(delegate() {
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
}
An anonymous method can use any class member variable, and it can also use any local variable defined at the scope of its containing method as if it were its own local variable.
An anonymous method can use generic parameter types, just like any other method. Because delegates can define generic parameters, an anonymous method can use generic types defined at the delegate level.
Anonymous Methods are quite useful because it replaces the need for creating a simple method in cases where only a delegate will suffice.
Adopted from Joval Lowy's article C# 2.0: Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes and C# Programmer's Reference: Anonymous Methods.
0 Comments:
Post a Comment
<< Home