Sunday, August 29, 2010

Anonymous Methods (Lambda vs anonymous method)

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods which enable you to omit the parameter list.

This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions

Lambdas are not allowed on the left side of the is or as operator. same as Anonymous methods

button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

Sample

// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };


http://www.codeproject.com/KB/cs/lambdaexpressions.aspx


The advantages of this "anonymous method" syntax are:

•You don't have to clutter up your class with private methods that are only used once in order to pass some custom code to a method.
•The code can be put in the place it's used in, rather than somewhere else in the class.
•The method doesn't have to be named.
•The return type is inferred from the signature of the delegate type that the anonymous method is being cast to.
•You can reference local variables in the "outer" method from within the anonymous method.

No comments: