Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent javascript closure in c#?

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?
}
like image 625
Kevin Tanudjaja Avatar asked Aug 15 '19 14:08

Kevin Tanudjaja


People also ask

Is there closure in C?

Although C was created two decades after Lisp, it nonetheless lacks support for closures.

What is closure of JavaScript?

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.

Is lexical scope same as closure?

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.


1 Answers

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();
like image 78
hardkoded Avatar answered Sep 17 '22 14:09

hardkoded