public SimpleForm()
{
addButton = new Button(...);
addButton.Click += delegate
{
MessageBox.Show ("Button clicked");
};
}
As the above code shows, you can use anonymous methods to declare the function logic inline. However C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block. Lambda Expressions are the natural evolution of C# 2.0's Anonymous Methods. Essentially, a Lambda Expression is a convenient syntax that is used to assign a chunk of code (the anonymous method) to a variable (the delegate). As an example,
employee => employee.StartsWith("D");
In this case, the delegates used in the above query are defined in the System.Query namespace as such:
public delegate T Func
public delegate T Func
So this code snippet could be written as:
Func
return s.StartsWith("D"); };
As you can see, the lambda expression is a lot more compact than the above one. Lambda Expressions are basically just a compact version of anonymous Methods, and you can use either of them or even regular named methods when creating filters for these query operators. Lambda Expressions, though, have the benefit of being compiled either to IL or to an Expression Tree, depending on how they are used.
Note that you can also pass parameters to Lambda expressions, which can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:
(int count) => count + 1 //explicitly typed parameter
(y,z) => return y * z; //implicitly typed parameter
No comments:
Post a Comment