Search code examples
c#delegateschaining

Can you chain the result of one delegate to be the input of another in C#?


I am looking for a way to chain several delegates so the result from one becomes the input of the next. I am trying to use this in equation solving program where portions are done by different methods. The idea is that when you are building the equation the program adds the delegates and chains them in a particular order, so it can be solved properly. If there is a better way to approach the problem please share.


Solution

  • This might help:

    public static Func<T1, TResult> Compose<T1, T2, TResult>(Func<T1, T2> innerFunc, Func<T2, TResult> outerFunc) {
        return arg => outerFunc(innerFunc(arg));
    }
    

    This performs function composition, running innerFunc and passing the result to outerFunc when the initial argument is supplied:

    Func<double, double> floor = Math.Floor;
    Func<double, int> convertToInt = Convert.ToInt32;
    
    Func<double, int> floorAndConvertToInt = Compose(floor, convertToInt);
    
    int result = floorAndConvertToInt(5.62);
    
    Func<double, int> floorThenConvertThenAddTen = Compose(floorAndConvertToInt, i => i + 10);
    
    int result2 = floorThenConvertThenAddTen(64.142);