Tutorial :Func or Predicate?



Question:

I've seen time and time again API (particularly in the .NET framework) that uses Func<TObject, bool> when Predicate<TObject> is seemingly a perfectly responsible option. What good reasons might an API designer have for doing so?


Solution:1

In LINQ, Func<T, bool> is used for things like Where so that the other overload which takes the index as well as the element is consistent:

IEnumerable<T> Where(IEnumerable<T> source, Func<T, bool> predicate)  IEnumerable<T> Where(IEnumerable<T> source, Func<T, int, bool> predicate)  

Personally I think the name Predicate is more descriptive, so I would use it in situations where there's no consistency issue like the one above. Mind you, there's something to be said for only needing to know about the Action and Func delegate types...


Solution:2

Consistency with the rest of LINQ?

(The "anomaly" has been noted, but with anonymous delegates and lambda functions it makes no difference, so almost never need to be aware of the difference.)


Solution:3

The Func<> delegates are the "new" way of specifying lambdas/delegates to methods. However, there just a handy set of delegates, and if there's a more specific delegate that does the same thing then go for that.

In your example I'd always go for the Predicate<> as it's much more self-documenting (assuming a predicate is what you want)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »