views:

307

answers:

3

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?

+2  A: 

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.)

Richard
Yes, but WHY did LINQ do it?
Michael Smith
I also don't think that "consistency" with the rest of LINQ is a <i>good</i> reason.
Michael Smith
See Jon's answer for one possibility.
Richard
A: 

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)

Sean
+6  A: 

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...

Jon Skeet
Yes, I'm afraid the answer isn't going to get any better than this. It's like some sort of code bureaucracy won over an aspect of purity. (i.e. Predicate should always be used despite consistency).
Michael Smith