Search code examples
c#.netlinqdelegatesfunc

Cannot use bool delegate(T) as Func<T, bool>?


I have created a delegate type which I use to pass methods around in my code. I though this would be a good idea because in case I would have to change the signature in future I just have to change it in one single place.

But my problem is now that although having the same signature the delegate seems not to be compatible with a Func so for example I cannot use it with LINQ without wrapping it again in a new function which will have performance penalties.

public delegate bool IsWalkable(Point point);

return directions.Any(isWalkable); // gives compile error CS1503    

Error CS1503 Argument 2: cannot convert from 'IsWalkable' to > 'System.Func<Microsoft.Xna.Framework.Point, bool>'

Am I overlooking something or will it be better to just use Func<Point, bool>?


Solution

  • Any requires not just any delegate but specifically Func<T, bool>, so you need either use Func<Point, bool> for isWalkable variable or do something like:

    return directions.Any(isWalkable.Invoke);
    
    // or 
    
    return directions.Any(x => isWalkable(x));