Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Lambdas at Creation

In javascript, it is common to use closures and create then immediately invoke an anonymous function, as below:

var counter = (function() {
    var n = 0;
    return function() { return n++; }
}());

Due to strong typing, this very verbose in C#:

Func<int> counter = ((Func<Func<int>>)(() =>
{
    int n = 0;
    return () => n++;
}))();

Is there a more elegant way to go about this type of thing in C#?

like image 875
bunglestink Avatar asked Nov 24 '11 16:11

bunglestink


People also ask

How can Lambda be invoked?

You can invoke Lambda functions directly using the Lambda console, a function URL HTTP(S) endpoint, the Lambda API, an AWS SDK, the AWS Command Line Interface (AWS CLI), and AWS toolkits.

How do I invoke Lambda function locally?

You can invoke your AWS Lambda function locally by using the sam local invoke AWS SAM CLI command and providing the function's logical ID and an event file. Alternatively, sam local invoke also accepts stdin as an event. For more information about events, see Event in the AWS Lambda Developer Guide.


2 Answers

You don't need the outer lambda in C#, it can be replaced by a simple block.

Directly invoking a lambda is a workaround for the lack of block level variables in Javascript (new versions support block scope using let).

Func<int> counter;

{
     int n = 0;
     counter = () => n++;
}
like image 162
CodesInChaos Avatar answered Oct 08 '22 01:10

CodesInChaos


The only thing I can suggest is Func<int> counter could be var counter, but can't think of anything else. Note that counter is still strongly-typed.


See also: var

like image 44
George Duckett Avatar answered Oct 08 '22 00:10

George Duckett