Consider this simple .js code:
const createCounter = () => {
let value = 0;
return {
increment: () => { value += 1 },
decrement: () => { value -= 1 },
logValue: () => { console.log(value); }
}
}
// Usage
const { increment, decrement, logValue } = createCounter();
I'm pretty sure c# support first class function, note that I don't want to use classes to remake the code above. What is the equivalent closure in c#?
I have made this:
public Func<WhatType?> CreateCounter = () => {
var value = 0;
return what?
}
Although C was created two decades after Lisp, it nonetheless lacks support for closures.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
The lexical scope allows a function scope to access statically the variables from the outer scopes. Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.
You could use a mix of ValueTuples and lambda expressions.
private static (Action increment, Action decrement, Action logValue) CreateCounter()
{
var value = 0;
return
(
() => value += 1,
() => value -= 1,
() => Console.WriteLine(value)
);
}
Usage
var (increment, decrement, logValue) = CreateCounter();
increment();
increment();
decrement();
logValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With