Question

Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing Func<T, bool> vs. Predicate<T>

I would imagine there is no difference as both take a generic parameter and return bool?

Was it helpful?

Solution

They share the same signature, but they're still different types.

OTHER TIPS

Robert S. is completely correct; for example:-

class A {
  static void Main() {
    Func<int, bool> func = i => i > 100;
    Predicate<int> pred = i => i > 100;

    Test<int>(pred, 150);
    Test<int>(func, 150); // Error
  }

  static void Test<T>(Predicate<T> pred, T val) {
    Console.WriteLine(pred(val) ? "true" : "false");
  }
}

The more flexible Func family only arrived in .NET 3.5, so it will functionally duplicate types that had to be included earlier out of necessity.

(Plus the name Predicate communicates the intended usage to readers of the source code)

Even without generics, you can have different delegate types that are identical in signatures and return types. For example:

namespace N
{
  // Represents a method that takes in a string and checks to see
  // if this string has some predicate (i.e. meets some criteria)
  // or not.
  internal delegate bool StringPredicate(string stringToTest);

  // Represents a method that takes in a string representing a
  // yes/no or true/false value and returns the boolean value which
  // corresponds to this string
  internal delegate bool BooleanParser(string stringToConvert);
}

In the above example, the two non-generic types have the same signature and return type. (And actually also the same as Predicate<string> and Func<string, bool>). But as I tried to indicate, the "meaning" of the two are different.

This is somewhat like if I make two classes, class Car { string Color; decimal Price; } and class Person { string FullName; decimal BodyMassIndex; }, then just because both of them hold a string and a decimal, that doesn't mean they're the "same" type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top