System.Predicate <T>: Is this really what it means, or is this what it is used for?

MSDN defines System.Predicate as follows :

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

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

Did I miss something?

+4
source share
4 answers

The CLR does not apply the semantics of type names.

So, Predicate<T> is just a delegate that accepts T and returns bool , but it should be used in places where a predicate is expected (test for a specific condition). This applies to a programmer who complies with this convention. If you need a similar delegate without a predefined semantic value, you can use Func<T, bool> , for example.

To the compiler, there is no functional difference between Predicate<T> or Func<T, bool> . But for another developer reading your code, it gives an important hint about what your code should do if you used it correctly.

Similarly, I have nothing to stop using System.DayOfWeek to store an arbitrary value from 1 to 7, which does not actually represent the day of the week. That would be stupid, but the compiler, of course, will allow me. It is up to you to make sure your code makes sense; the compiler cannot do this for you.

+10
source

This is what I predicate, this term is borrowed from predicate logics .

Then, of course, you can make other functions that are not strictly predicates that have the same function signature.

+3
source

You think this is a predefined delegate, but the most common use in extensibility allows you to determine, outside a method call, whether a condition is met.

Many now prefer to use Func<T,bool> rather than Predicate<T> , given the more common use within the structure itself.

+1
source

I think that the definition forces a special prototype into specific use, and the delegate can be used like any function, only the system one. The editor can be used for the collection predicate function (I would say that this looks like a prototype of a C ++ pointer function)

0
source

All Articles