Reputation: 8680
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?
Upvotes: 21
Views: 3454
Reputation: 62002
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.
Upvotes: 0
Reputation: 27857
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)
Upvotes: 2
Reputation: 37827
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");
}
}
Upvotes: 17
Reputation: 413
They share the same signature, but they're still different types.
Upvotes: 18