7

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

2
  • 1
    Func<int> counter could be var counter, but can't think of anything else. Note that counter is still strongly-typed. Commented Nov 24, 2011 at 16:52
  • 1
    As a side note, the verbosity is not just due to strong typing. In corresponding code in F# (which is strongly-typed just like C#), you don't have to declare any types.
    – svick
    Commented Nov 24, 2011 at 17:06

4 Answers 4

14

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++;
}
6
  • A legitimate use of a semicolon immediately preceding an opening brace? Is this real life?
    – BoltClock
    Commented Nov 24, 2011 at 17:03
  • The braces there are not required at all. It's just an assignment. The closure isn't captured, though, so I don't think this satisfies the question. Commented Nov 24, 2011 at 17:14
  • @BoltClock Putting an empty line before the block is probably a good idea here to make it clear that it's a standalone block. Commented Nov 24, 2011 at 17:15
  • 1
    @RichardHein The braces aren't required in this case, because only one counter is used. But if you create multiple counters inside a function, then they are sometimes required. But I don't understand what capture you're missing. Commented Nov 24, 2011 at 17:17
  • @CodeInChaos AH, I see what you mean. By having n in the block you are closing over it when you return () => n++ ... cool. +1 Commented Nov 24, 2011 at 17:22
1

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

3
  • The cast to Func<Func<int>> is still necessary, since var doesn't work on lambdas, since they have no well defined type. So var doesn't save much verbosity here. Commented Nov 24, 2011 at 16:59
  • Cannot assign lambda expression to an implicitly-typed local variable. Commented Nov 24, 2011 at 17:02
  • 2
    var counter does work, as long as you keep the cast or use new Func<Func<int>>. Commented Nov 24, 2011 at 17:08
1

There's not a much nicer way, but the cast is a bit confusing, so I'd prefer this:

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

Edit: As CodeInChaos just asked, the outer lambda seems redundant.

Edit 2: No, it's not redundant because you want a closure over n. So either the way above or:

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

Edit 3: Since I am not sure if you want to reuse the counter function, such that it can be reinitialized, which of the two scenarios (or another scenario) do you want:

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

        Console.WriteLine("Counter0:");
        var count0 = counter0();
        for (var i = 0; i < 5; i++)
        {
            Console.WriteLine(count0());
        }

        var count1 = counter0();
        for (var i = 0; i < 5; i++)
        {

            Console.WriteLine(count1());
        }

        Console.WriteLine("Counter1:");
        Func<int> counter1 = new Func<Func<int>>(() => { var n = 0; return () => n++; })();

        for (var i = 0; i < 5; i++)
        {
            Console.WriteLine(counter1());
        }

        for (var i = 0; i < 5; i++)
        {
            Console.WriteLine(counter1());
        }

Output: Counter0: 0 1 2 3 4 0 1 2 3 4 Counter1: 0 1 2 3 4 5 6 7 8 9

5
  • 1
    You can also use var counter in this case, it was the first thing I came to (and tested) as well. Commented Nov 24, 2011 at 17:10
  • @ChrisWalsh Yes, absolutely (so +1), but in this case, Func<int> makes it more clear what counter is, so I explicity typed it. Commented Nov 24, 2011 at 17:20
  • counter should be a Func<int> because the invokation of the outer lambda happens before assigning to counter in the OP's code. So the second code piece doesn't work as desired. x=counter()(); y=counter()(); both x and y are 0. Commented Nov 24, 2011 at 17:27
  • @CodeInChaos I am not sure what the OP wants, so I updated my answer. Commented Nov 24, 2011 at 17:40
  • the example was trivial... I was just looking for the cleanest way to close a "private" variable in a lambda in C#, similar to what is done in javascript by immediately invoking an anonymous function. @CodeInChaos pointed out that C#'s block scoping can handle this quite elegantly. Commented Nov 25, 2011 at 4:30
-1

is the cast really necessary? it depends on how you are using the func.

could simply do something like

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

this seems a little strange, though, declaring the variable inside the func and i'm pretty sure it's not really what you intend.

6
  • It is necessary because lambdas need to be explicitly typed on their own.
    – BoltClock
    Commented Nov 24, 2011 at 17:04
  • you're right. that was a bad answer. edited to hopefully be feasible now.
    – Dave Rael
    Commented Nov 24, 2011 at 17:12
  • Lambdas don't have a well defined type, since there are many delegate types compatible with a certain signature, and C# doesn't treat Func<...> as special. In most scenarios one can choose between using a cast[or new DelegateType(...)]+var or an explicit variable type and no cast. The invocation in this code requires the cast here, so you can't just use an explicit variable type instead of a cast here. Commented Nov 24, 2011 at 17:12
  • 1
    This doesn't compile. This is the closest thing to your answer that compiles, but note that it is incorrect: Func<int> counter = () => { int n = 0; return n++; }; Commented Nov 24, 2011 at 17:14
  • that is what i meant. edited to match. and it is correct - it's exactly the same code as in the question. i noted that it's probably not what was intended, but it matches what was in the question (and it would be easy to take the counter outside the func to be more sensible.
    – Dave Rael
    Commented Nov 24, 2011 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.