Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 998
richard Avatar asked Dec 10 '22 07:12

richard


1 Answers

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.

like image 143
Sven Avatar answered Jan 26 '23 00:01

Sven