The sample below, shows uses a predicate
to evaluate a condition with hard-coded value of 100000. There is no way to add an additional parameters to the FindPoints
method, for it would violate the predicate param constraint.
This brings the value of using predicates into question. Obviously Lambda solves this problem..but none the less, can anyone elaborate on the usefulness of predicates in real life scenarios, given this seemingly strange constraint.
Why would anyone use predicates if they don't accept parameters other than T?
using System;
using System.Drawing;
public class Example
{
public static void Main()
{
// Create an array of Point structures.
Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
// Define the Predicate<T> delegate.
Predicate<Point> predicate = FindPoints;
// Find the first Point structure for which X times Y
// is greater than 100000.
Point first = Array.Find(points, predicate);
// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
}
private static bool FindPoints(Point obj)
{
return obj.X * obj.Y > 100000;
}
}
// The example displays the following output:
// Found: X = 275, Y = 395
EDIT: Lambda usage to do the same thing, below.
using System;
using System.Drawing;
public class Example
{
public static void Main()
{
// Create an array of Point structures.
Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
// Find the first Point structure for which X times Y
// is greater than 100000.
Point first = Array.Find(points, x => x.X * x.Y > 100000 );
// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
}
}
// The example displays the following output:
// Found: X = 275, Y = 395
This is from MSDN. The article gives good examples, but does not seem to address my question.