Lambdas
Create anonymous methods using a more concise syntax.
We'll cover the following...
Overview
Lambdas are a simpler way to declare anonymous methods, though the syntax might look a bit tricky at first.
Let’s look at an example. We’ll rewrite the code from the previous lesson:
Syntax and usage
Let’s disassemble the lambda expression to understand its individual parts:
(operand1, operand2): These are the parameters of the anonymous method. The types of parameters are omitted because they’re retrieved implicitly from the delegate’s signature.=>: This is the method body. Thereturnkeyword isn’t necessary. Unless a statement is an assignment or some action that doesn’t generate a value, thereturnkeyword is injected and the value is returned. In our case, the result ofoperand1 + operand2is returned.
If an anonymous method accepts a single parameter, parentheses around the parameters can be omitted:
Empty parentheses are used if the lambda expression doesn’t accept any parameters. The following code also demonstrates a case when a lambda doesn’t return any value.
Notice that we don’t have to state the parameter types when declaring lambdas. However, if the delegate has parameters modified with the ref or out keywords, then we must provide the types as well:
Lambdas as method parameters
Lambdas can serve as method parameters, just like delegates and anonymous methods. In the following code, we receive the same end result as the previous code playground, but with different implementation: