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
Func<int> counter
could bevar counter
, but can't think of anything else. Note thatcounter
is still strongly-typed.