Predicate

L

Lit

Hi,

Can someone explain this:

<this is from Using generic- By Ludwig Stuyck>

string nameToFind = "Ludwig Stuyck";
PersonNameFilter personNameFilter = new PersonNameFilter(nameToFind);

// Create a new predicate, that uses the FilterByName method to determine
whether the person has been found

Predicate<Person> filterByName = new
Predicate<Person>(personNameFilter.FilterByName);

// Find the person in the collection

Person foundPerson = persons.Find(filterByName);

?? Are we passing a method to a method or what

?? is this similar to anonymous methods.

?? can not see the fully understand it or see the full power yet, but I
know/heard it is very powerful

Thanks

Lit.
 
A

AlexS

Look at Predicate Generic Delegate in MSDN, which provides basic sample.

Extract from sample
// To find the first Point structure for which X times Y
// is greater than 100000, pass the array and a delegate
// that represents the ProductGT10 method to the Shared
// Find method of the Array class.
Point first = Array.Find(points, ProductGT10);

// Note that you do not need to create the delegate
// explicitly, or to specify the type parameter of the
// generic method, because the C# compiler has enough
// context to determine that information for you.

// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);

Note that you don't need create delegate and you can use in-class method:

// This method implements the test condition for the Find
// method.
private static bool ProductGT10(Point p)
{
if (... return false;
}
}
}

As you can see you pass "method to method" - namely, delegate, which is
somewhat similat to anonymous method - if to forget that you can use
ProductGT10 also as standard static method.

HTH
Alex
 
M

Marc Gravell

The Predicate<T> can be thought of as a (typed) function pointer, so
yes this is essentially passing a method to a method; this allows the
Find method to invoke the method on each item (Person) in turn, and
see if it is a match (by returning true). How you construct the
predicate is where it gets fun; the way shown here is obviously using
a class definition - but as you can see (I imagine the
PersonNameFilter code is shown) this is a pain, and not very versatile
as you need more and more classes / methods every time you have a
different filter. Anonymous methods are far more concise, but do
*exactly* the same thing; it is the C# compiler that writes the
PersonNameFilter class and FilterByName method (although the names
will be different of course).
This allows us to simply use:
Person found = persons.Find(delegate (Person p) {return p.Name ==
nameToFind;});

In C# 3.0 (.NET 3.5) we can use Lambda expressions to do the same even
tidier:
Person found = Find(p=>p.Name==nameToFind);

To illustrate what I meant about function pointers (the first part),
internally (courtesy of reflector) the List<T>.Find method is shown
below.

Marc

public T Find(Predicate<T> match)
{
if (match == null)
{

ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < this._size; i++)
{
if (match(this._items))
{
return this._items;
}
}
return default(T);
}
 
L

Lit

Thanks AlexS and Marc

I have a headache but trying to see the big picture.
Please let me see If I understand you both here.

we are invoking a method passing parameters and one of them is a pointer to
a method.

So If I have a generic method that is mostly the same but one element of it
needs a specialized Method ( the one I am passing ) then this is where it is
useful???

do you have few problems where you see this as a solution the only good
solution or generic solution. the string theory of everything?

Is this most useful for collections?

Is this useful for Mathematical problems.

where else have you seen this useful? Artificial Intelligence, super
dynamic polymorphic systems or what?

I am not at the point of pulling my hair yet... but getting gray.

Enlighten me please,

Thank you,

Lit
 
J

Jon Skeet [C# MVP]

?? Are we passing a method to a method or what

?? is this similar to anonymous methods.

?? can not see the fully understand it or see the full power yet, but I
know/heard it is very powerful

Okay, there are three concepts here:

1) Delegates
2) Generics
3) Anonymous methods

Anonymous methods are *one* way of creating delegate instances.
You don't have to bring in generics to understand delegates, but once
you understand delegates and generics separately, the two work together
very easily.

Here's my article about delegates (and events) - hope it helps:
http://pobox.com/~skeet/csharp/events.html
 
B

Bob Johnson

RE:
<< where else have you seen this useful >>

I have a Windows Forms application that maintains a collection of "people"
objects with properties for FirstName, LastName, SSN, etc. I provide the
users with the ability to search for people by FirstName, LastName, (or
both), SSN, etc.

As the user types, I display a list of people that match what has been typed
in. I make use of the Predicate<T> delegate to search the "master
collection" of people objects. Different methods search for a match based on
the property the user is searching [actively typing] on.

Very useful. It's not rocket surgery - quite simple once understood.
 
M

Marc Gravell

Most of your questions relate to the usage of delegates (not generics
nor anonymous methods).

The biggest use (by far) of delegates is to support events, but this
isn't what is happening here. The delegate-as-a-function-pointer
scenario is useful (especially when writing re-usable base classes,
such as collections) when we know a "pattern of behavior", but not the
details - i.e. (in this case) "return true if the given item is what
we are looking for". But delegates aren't the only option here -
interfaces could be used equally, i.e. compare and contrast:

public delegate bool Predicate<T>(T value); // standard definition
public interface IPredicate<T> {bool Match(T value);} // i'm making
this up...

Not much real difference - the Find method could equally accept an
IPredicate<T> and call the Match() method each time. In fact, this
duality is quite common - look at IComparer<T> and Compison<T> (both
used typically to provide custom sorting). I'd struggle to give many
reasons why either is much better... delegates allow for anonymous
syntax (but that is a function of the compiler; if delegates didn't
exist perhaps there would be "anonymous interface implementation"...),
and can be used on static methods (compares perhaps to a singleton for
a "static" concrete interface implementation)... compatible delegates
can be created from multiple different (but suitable) methods on the
same class (compare perhaps to multiple nested private Types, each
implementing the interface differently).

Not sure I really answered much there...

Marc
 
L

Lit

Bob,

I see a good example here, but need a few lines of details.

Lets say I am using your program and typing the first character of a last
name
then what do you ( your application) do.

Are you calling just one method passing it a method as a parameter telling
it to search by last name.

please give me a bit more detail to help me understand this.

you are right once I understand rocket science its easy.

Thank you,

Lit
 
J

Jon Skeet [C# MVP]

Very useful. It's not rocket surgery - quite simple once understood.

Do you include anonymous types using captured variables in "quite
simple"? :)
 
J

Jon Skeet [C# MVP]

Marc Gravell said:
Most of your questions relate to the usage of delegates (not generics
nor anonymous methods).

Oi! Stop stealing my thoughts! :)
The biggest use (by far) of delegates is to support events, but this
isn't what is happening here.

It's worth pointing out that although events are probably the biggest
use of delegates in C# 1 and 2 (closely followed by starting threads
and using Control.Invoke/BeginInvoke), I'm expecting C# 3 and LINQ will
change the balance a lot over time. Even .NET 2.0 encourages more use
of delegates, particularly for things like comparisons used in sorting.
List<T> has some nice features on that front.

I'd urge all C# 1 and 2 developers to make sure they're really
comfortable with delegates now, before C# 3 is released: that way
you'll be a lot better prepared come the revolution.
 
B

Bob Johnson

I was being sarcastic...

.....thus I said it's like "rocket surgery" which conveys that I don't even
understand how to say "rocket science" or "brain surgery" without confusing
them. not as funny when it has to be explained...

:)
 
J

Jon Skeet [C# MVP]

Bob Johnson said:
I was being sarcastic...

....thus I said it's like "rocket surgery" which conveys that I don't even
understand how to say "rocket science" or "brain surgery" without confusing
them. not as funny when it has to be explained...

I didn't take it as sarcasm because until you bring in anonymous
methods and captured variables etc, delegates really *aren't* very
complicated, in my view. They take a little while to get your head
round the basic concept, but after that it's not a problem.

Captured variables, on the other hand... incredibly useful, but so easy
to get wrong. Hopefully we'll all become better at using them over
time, myself very much included.
 
B

Bob Johnson

Hi Jon,

RE:
<< delegates really *aren't* very complicated>>
and
<< They take a little while to get your head round the basic concept>>

I agree. And to exapand a bit - what was challenging for me (as someone just
starting to get comfortable with delegates) is the documentation and chatter
about all sorts of "different delegates" - Predicate<T>, Comparison<T>,
Action<T>; these are presented and talked about as if they were different
things with different capabilities (when their *usage* is primarily how they
differ). To someone new to the concept this chatter presents the *illusion*
that delegates are more complicated than they really are.

It finally dawned on me, when trying to figure out specifically how all
these delegates differed, that delegates really are "just delegates" at the
end of the day. None of those listed above (or elsewhere for all that
matters) really have any differing capabilities (except perhaps for the base
Delegate vs MulticastDelegate). You helped to confirm this ("all those
delegates are just delegates") in my post on the 22nd of this month (subject
= What differentiates Delegates Beyond Name/Signature).

So, IMHO, it seems to me that it takes a little while to get one's head
around the basic concept BECAUSE delegates are aften presented and talked
about as if they are much more than they are.

Thanks again for the clarification.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top