5

Is there any value to using a predicate over a normal delegate? Taking the example below, I don't see any.

Predicate<int> isEven = delegate(int x) { return x % 2 == 0; };
Console.WriteLine(isEven(1) + "\r\r");

Func<int, bool> isEven2 = delegate(int x) { return x % 2 == 0; };
Console.WriteLine(isEven(1) + "\r\r");
naveen
  • 53,448
  • 46
  • 161
  • 251
Ryan
  • 51
  • 2

5 Answers5

7

They're effectively the same. Predicate<T> is a delegate type that was added to the base class library for list and array Find() methods. This was before LINQ, which was when the more general Func family of delegates were introduced. You could even write your own delegate type and use that:

delegate bool IntPredicate(int x); 

static void Main()
{
   IntPredicate isEven = delegate(int x) {return x % 2 == 0;};
   Console.WriteLine(isEven(1) + "\r\r");
}
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • +1, though I am often torn too between the rather ugly looking (but generalized) `Func` and the nicer looking `Predicate`. Especially considering Func says nothing about its intended usage whereas Predicate sorta does. – Josh Jan 04 '11 at 04:02
  • I hardly ever have to specify the delegate type as I just enter them as type-inferenced lambdas, e.g., `foo( x => x % 2 == 0);` – Mark Cidade Jan 04 '11 at 04:04
  • With `Predicate`, the intended usage of the delegate is more explicit. Then again, if you do a good job of naming the parameter, the difference might be negligible. E.g. `public SomeObj Find(Func isMatch) { }` vs `public SomeObj Find(Predicate isMatch) { }`. – Merlyn Morgan-Graham Jan 04 '11 at 04:14
0

Predicate is a delegate. It is a delegate defined in the .Net framework 3.0. Predicate always returns a boolean value. So both delegates in your code are equivalent. Other delegates provided by .Net are Func and Action. Action returns void.

AlwaysAProgrammer
  • 2,927
  • 2
  • 31
  • 40
0

Only that a bunch of the Microsoft-provided library code uses it.

For example: List.FindAll needs to be passed a Predicate.

For your own code, you can use whichever one you like. You could even use Converter<int, bool>.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

They're effectively the same. That said, extension methods (in your personal library or someone else's) are more likely to be defined on Func<T, TResult> so I'd prefer that one.

Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32
0

For consistency with LINQ I tend to define Func<T, bool> over Predicate<T>.

Marc L.
  • 3,296
  • 1
  • 32
  • 42