What is the equivalent javascript closure in c#?
Asked Answered
A

2

8

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?
}
Aba answered 15/8, 2019 at 14:52 Comment(2)
You could use a Map of functions. I don't know if there's such a thing as destructuring in C# (or similar)Atalee
could you provide any examples or references to Map of functions which will hold the value state?Aba
P
13

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();
Poundfoolish answered 15/8, 2019 at 15:1 Comment(0)
R
0

Check out the following code using Dictionary to Map enumerated data types with an Action Delegate

void Main()
{
    OperationActionDictionary[Operation.Increment](); // Execute Increment
    OperationActionDictionary[Operation.Increment](); // Execute Increment
    OperationActionDictionary[Operation.Decrement](); // Execute Decrement
    OperationActionDictionary[Operation.LogValue]();  // Execute LogValue
}

public enum Operation
{
    Increment,
    Decrement,
    LogValue
}

public static int Value = 0;

public Dictionary<Operation,Action> OperationActionDictionary = new Dictionary<Operation, Action>
{
    [Operation.Increment] = () => Value += 1,
    [Operation.Decrement] = () => Value -= 1,
    [Operation.LogValue] = () => Console.WriteLine($"Value :: {Value}")
};

Only catch here or in any other code for modifying a shared Value object would be in case it is Multi thread access, then you need to take care of thread safety in this case using Interlocked.Increment or Interlocked.Decrement

Ralphralston answered 19/8, 2019 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.