0

I'm a beginner in C#, just a question on differences between Predicate and Func delegate in C#

we know that:

public delegate bool Predicate<in T>(T obj);

public delegate TResult Func<in T, out TResult>(T arg);

so if I do like

Func<Product, bool> firstdelegate = ...

and

Predicate<Product> secondpredicate = ...

aren't they the same? I mean they all do the same thing, so why in LINQ' Where() method takes Func type delegate instead of Predicate?

amjad
  • 3,048
  • 1
  • 11
  • 42
  • It would be odd if LINQ use `Predicate` in `Where`, but `Func` everywhere else, including the other overload of `Where`. – user4003407 Mar 08 '19 at 06:59
  • Is `class Point1 { int x,y; }` the same as `class Point2 { int x,y; }`? Definitely no, but yes they have similarities. But a method that requires Point1 will never accept Point2 instance as a parameter. Delagate are not compatible by signature. – Mikant Mar 08 '19 at 07:02

1 Answers1

7

Predicate<T> was introduced in .NET 2.0 with the introduction of generics. It's a delegate taking one parameter and returning a bool.

However, with the introduction of LINQ in .NET 3.5, a need was identified for two families of generic types - Func and Action (the difference being on whether they return anything) taking up to 16 41 generic input parameters and being generic in their return types. If Func had existed first, Predicate<T> would never have been created in the first place. It's an unnecessarily specialized delegate type.

For backwards compatibility reasons though, they cannot now remove Predicate<T> from the framework. Some may argue that its name does convey specific semantic meaning but I'd struggle to identify many situations where any Func<T,bool> (or Func<T1,T2,bool>, etc.) wouldn't be considered a predicate.


14 in .NET 3.5, 16 in .NET 4 and later.

Matias Kinnunen
  • 6,700
  • 3
  • 32
  • 33
Damien_The_Unbeliever
  • 227,877
  • 22
  • 326
  • 423