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#?
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).