Search code examples
c#.netunity-game-enginepredicate

How to combine multiple Func<> delegates


How can I combine multiple Func delegates?

Assume I have two delegates

Func<bool> MovementButtonHold() => () => _inputSystem.MoveButtonHold
Func<bool> IsFreeAhead() => () => _TPG.IsFreeAhead();

Is there any way to combine these two delegates to one Func<bool> delegate?

Something like:

And

Func<bool> delegate1 = MovementButtonHold() && IsFreeAhead();

Or

Func<bool> delegate2 = MovementButtonHold() || IsFreeAhead();

Solution

  • In your code MovementButtonHold and IsFreeAhead are not delegates, they are methods that return delegates. So to combine them you need something like this:

    Func<bool> delegate1 = () => MovementButtonHold()() && IsFreeAhead()();
    Func<bool> delegate2 = () => MovementButtonHold()() || IsFreeAhead()();
    

    Note the ()() weird syntax above. The first () is to call the method and return the delegate, the second () is to call the delegate the return boolean result. Then you create an inline function to perform "AND" or "OR" operations on the outputs, and assign the inline function to delegate1 or delegate2

    Unless you have a reason to make MovementButtonHold and IsFreeAhead return delegates you can simplify their implementations as follows to simply return the boolean result.

    bool MovementButtonHold() => _inputSystem.MoveButtonHold;
    bool IsFreeAhead() => _TPG.IsFreeAhead();
    
    Func<bool> delegate1 = () => MovementButtonHold() && IsFreeAhead();
    Func<bool> delegate2 = () => MovementButtonHold() || IsFreeAhead();