4

MSDN defines System.Predicate this way:

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

Is this really what it means, or just what it is typically used for? Because to me it just looks like a predefined delegate whose method must take an object of type T and return a bool - and nothing more.

Am I missing something?

richard
  • 12,263
  • 23
  • 95
  • 151

4 Answers4

10

The CLR doesn't enforce semantics of type names.

So yes, Predicate<T> is just a delegate taking a T and returning a bool, but it's meant to be used in places where a predicate (a test for a certain condition) is expected. It's up to the programmer to respect that convention. If you need a similar delegate without a predefined semantic meaning, you could use Func<T, bool>, for example.

To the compiler, there is no functional difference between a Predicate<T> or a Func<T, bool>. But to another developer reading your code, it provides an important hint as to what your code is supposed to do, provided you used it correctly.

Similarly, there's nothing to stop me from using System.DayOfWeek to store an arbitrary value between 1 and 7 that doesn't actually represent a day of the week. It would be a stupid thing to do, but the compiler will certainly let me. It's up to you to make sure your code makes sense, the compiler can't do that for you.

Sven
  • 21,903
  • 4
  • 56
  • 63
3

That is what i predicate is, the term is borrowed from predicate logics.

Then it is of course possible to make other functions, which are not strictly predicates, that have the same function signature.

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
1

You're spot on in thinking it's a predefined delegate but it's most common usage is in extensibility to determine outside a method call whether a condition is met.

Many now prefer to use the Func<T,bool> rather than Predicate<T> given it's more common usage within the framework itself.

Darren Lewis
  • 8,338
  • 3
  • 35
  • 55
  • Seems odd they would _define_ it that way. I wish they would just define it for what it is, and then say "oh by the way, this is the most common usage". It's a bit confusing as is. – richard Jul 20 '11 at 07:03
  • 1
    @Richard: Naming it `Predicate` is an attempt to make the idiom of accepting a filtering function that returns bool more explicit in the code. *edit* Sven edited his answer to cover this rationale :) – Merlyn Morgan-Graham Jul 20 '11 at 07:07
0

I think the definition forces a special prototype in specific usage, while the delegate can be used as any function, only a System.Predicate can be used for a collection predicate function (i would say it is like a C++ pointer function prototype)

NirMH
  • 4,769
  • 3
  • 44
  • 69