C# 3.0

  • Thread starter Thread starter Guest
  • Start date Start date
If by "predicate delegate" you mean a Predicate<T>, then this is just
a way of expressing a logical test (and is 2.0, not 3.0 - although 3.0
can produce a predicate from an expression-tree).

It has the signature "bool Predicate<T>(T value)", meaning that given
an object of type T, the method returns true or false - useful for
filters etc.

A delegate (instance) in this context is, as always, an instance of a
method-pointer to such a method - i.e.

public static bool IsEven(int value) {
return value % 2 == 0;
}

then to get a delegate instance:
Predicate<T> isEven = IsEven; // or, = new Predicate<T>(IsEven) in
longhand

and then you can evaluate
bool fiveIsEven = isEven(5);

Of course - in reality you wouldn't do this ;-p Predicates are useful
when the component executing the expression (not in the C#3.0
sense...) cannot possibly know the expression itself - i.e. List<T>
can't know that I am interested in even numbers...

However, you don't need this... you can be a lot more terse; so if I
have a List<int>, I can use either:
List<int> evenList = biggerList.FindAll(IsEven);
or alternatively using anonymous syntax:
List<int> evenList = biggerList.FindAll(delegate (int value) {return
value % 2 == 0;});

C# 3.0 introduces an easier "lambda" way of expressing this:

List<int> evenList = biggerList.FindAll(v => v % 2 == 0);

Does that help any?
 
Oops:
Predicate<T> isEven = IsEven;
should have read
Predicate<int> isEven = IsEven;

Marc
 
Predicate delegate as in anonymous expression or as in Lambda expression?
 

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

Back
Top