Search code examples
pythonc#functools

What is C# equivalent of Python's functools.partial?


In python we have a functools.partial mechanism. What would be a valid C# equivalent?

For those unfamiliar with the concept, I am looking for the general case, but it could be anything, even:

def add(a: int, b: int):
    return a + b

add_to_one = partial(add, 1)
add_to_one(2)  # This will return 3

Solution

  • Based on your example, the best I can think of that comes close, is a Func delegate.

    This provides a method of defining a local function, based on pretty much anything. In this case it's defined in the local Main scope.

    Usage:

    using System;
                        
    public class Program
    {
        public static void Main()
        {
           // Func<,> type: input is 'int', output will be 'int'
           // 'c' = input argument.
           // '=>' indicates what will be done with it.  
           Func<int,int> add_to_one = (c) => Add(c,1);
    
           //call 'add_to_one' as a normal method.
           int result = add_to_one(2);
           
           Console.WriteLine(result);
        }
        
        //example method
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
    

    Output:

    3
    

    As for the general case:

    Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args.

    This part is covered. You'll have a callable variable behaving like a method/function.

    As for this:

    If additional keyword arguments are supplied, they extend and override keywords.

    It is possible, the construction is expandable to many more input variables, e.g.:

    // 3 inputs
    // output is string
    Func<int,string,double,string> foo = (i,s,d) => $"int: {i}, string: {s}, double {d}";