Search code examples
c#delegatespartial

Delegate partial function in C#?


I've written some calculate delegates which are passed as parameters.

private delegate int CalculateDelegator(int value1, int value2);
CalculateDelegator addWith = add;
CalculateDelegator divWith = div;

private static int add(int value1, int value2) {
    return value1 + value2;
}

private static int div(int value1, int value2) {
    return value1 / value2;
}

The method link(CalculateDelegator method, int value2) which receives addWith as parameter holds value1 and the method which calls link holds value2. So I call link() always with passing value2 as seperate paremeter.

Is there a way of passing the calculating method including the first parameter: link(addWith(value2))? (e.g. as a partial function like in Scala)


Solution

  • No, something like that isn't directly possible in C#.

    What you can do is something like the following:

    int link(Func<int, int> addWithValue2)
    {
        return addWithValue2(value1);
    }
    

    You would call it like this:

    link(v1 => addWith(v1, value2));
    

    BTW: I think the concept you are describing is called currying and there is a project that tries to bring it to C#: https://github.com/ekonbenefits/impromptu-interface/wiki/UsageCurry. It basically uses the approach shown in this answer.