Ok, very silly question.
x => x * 2
is a lambda representing the same thing as a delegate for
int Foo(x) { return x * 2; }
But what is the lambda equivalent of
int Bar() { return 2; }
??
Thanks a lot!
The body of a lambda expression can contain zero, one or more statements. When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
These are for single–line lambda expressions having void return type. Type 1: No Parameter. Type 2: Single Parameter. The type and return type of the lambdas are automatically inferred.
Using Lambda ExpressionsThe lambda expression should have the same number of parameters and the same return type as that method.
The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created.
The nullary lambda equivalent would be () => 2
.
That would be:
() => 2
Example usage:
var list = new List<int>(Enumerable.Range(0, 10)); Func<int> x = () => 2; list.ForEach(i => Console.WriteLine(x() * i));
As requested in the comments, here's a breakdown of the above sample...
// initialize a list of integers. Enumerable.Range returns 0-9, // which is passed to the overloaded List constructor that accepts // an IEnumerable<T> var list = new List<int>(Enumerable.Range(0, 10)); // initialize an expression lambda that returns 2 Func<int> x = () => 2; // using the List.ForEach method, iterate over the integers to write something // to the console. // Execute the expression lambda by calling x() (which returns 2) // and multiply the result by the current integer list.ForEach(i => Console.WriteLine(x() * i)); // Result: 0,2,4,6,8,10,12,14,16,18
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