Given the following sample codes:
static void SomeMethod()
{
Action<int,int> myDelegate;
//...
myDelegate = delegate { Console.WriteLine( 0 ); };
myDelegate = delegate() { Console.WriteLine( 0 ); }; // compile error
}
What is the difference between
myDelegate = delegate { Console.WriteLine( 0 ); };
and
myDelegate = delegate() { Console.WriteLine( 0 ); };
?
In this example, the second statement generates compile error while the first one does not.
Lambda expressions A Lambda expression is an anonymous function that can contain expressions and statements. They are also used to create delegates or expression tree types. Expressions can be mystifying, but simply put, they are nothing more than code represented as data and objects in a . NET application.
Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.
An anonymous method has the syntax delegate
parameter-list {
statement-list }
. The parameter list is optional.
If you omit the parameter list then the anonymous method is compatible with any delegate type where the parameters are not marked "out".
If you supply the parameter list then it must match the delegate parameter types exactly.
In your first case you are omitting it, and in the second case you are supplying it but not matching the delegate parameters. So delegate {}
is legal, and delegate (int i, int j) { }
is legal, but delegate () {}
is not.
In any event, you are probably better off using a lambda expression; it is the more common syntax in new code: (i, j)=>{ }
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With