Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression with a void input

Tags:

c#

lambda

c#-3.0

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!

like image 207
Luk Avatar asked Oct 02 '09 12:10

Luk


People also ask

Can lambda expression have empty body?

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.

What is the return type of lambda expression void?

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.

Can lambda expression have return type?

Using Lambda ExpressionsThe lambda expression should have the same number of parameters and the same return type as that method.

What does [=] mean in lambda function?

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.


2 Answers

The nullary lambda equivalent would be () => 2.

like image 75
outis Avatar answered Oct 08 '22 10:10

outis


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 
like image 23
Ahmad Mageed Avatar answered Oct 08 '22 11:10

Ahmad Mageed