If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. I'm just getting my head around delegates. I found that I could set up a predicate (small "p") in two ways:
Code:
Dim mypred1 = New Predicate(Of Object)(Function(x) x > 2)
Dim mypred2 = New Func(Of Object, Boolean)(Function(x) x > 2)
They both work as expected and return True or False when presented with integers either > or <= 2, respectively. I'm guessing that "Predicate" is essentially syntactic sugar but want to confirm that guess.
1. Is my use of Predicate in the first expression merely the use of syntactic sugar wrt the second?
2. Are there ways Func differs from Predicate when only one input argument is accepted and the result must be Boolean?
That is, can I say:
Code:
Predicate(Of T)(AddressOf Delegate)
is equivalent to
Code:
Func(Of T, Boolean)(AddressOf Delegate)
Predicate(Of T) is its own type. It's a named delegate, and as such can be used wherever code is expecting a method with matching signature.
Func(Of T, Boolean) is likewise its own type. It represents a function that takes a parameter of type T and returns a Boolean. This matches the signature defined by Predicate(Of T) so instances of both of them can be used interchangably.
1) Predicate is not syntactic sugar, for Func. However, as explained above, they are equivalent.
2) Yes, there is adifference: Func(Of T, Boolean) represents a function that returns a boolean value given an input object of type T. Predicate(Of T) represents a statement about the input object that can be evaluated as either true or not true. It has a stronger semantic meaning in that it specifically represents a predicate, not just a function that returns a boolean. I think I get it. It looks like, for practical purposes, they are are interchangeable, unless I'm missing an example where one would work but the other would not.
I'm seeing however, that choosing Predicate because of its stronger semantic meaning can lead to clearer code when appropriately used. Technically, they accomplish the exact same thing. You can google it and find tons of articles discussing this.
What you WILL see often times is that it is used in LINQ queries to define a filter of what it to be selected and the LINQ queries them selves ask for a "predicate<t> filter" and I don't think you can define a Func<T, bool> there. Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.