2009-08-06

Predicate Delegation

C#2.0 has introduced several interesting grammars into simple c++ style coding. "Predicate Delegation" is one of them. From the point of linguistic semantics, a predicate is an expression that can be true of something. In the C#, predicate delegation is a reference of function, whose return value is true or false. Why do we need it? Because predicate delegation works like a filter and make search operation among a collection (List, IEnumerable) simpler and clearer. Let me paste the example from here

Here is a common c type function to return odd numbers from an array.


int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] odds = GetOdds(numbers);
private static int[] GetOdds(int[] numbers)
{
int[] odds = new int[numbers.Length];
int counter = 0;
for (int i = 0; i < numbers.Length; i++)
{
if ((numbers[i] % 2) != 0)
{
odds[counter++] = numbers[i];
}
}
return odds;
}
Using Predicate Delegation the above program can be simplified as
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };        
int[] odds = Array.FindAll<int>(numbers, IsOdd);

private static bool IsOdd(int number)
{
return ((number % 2) != 0);
}
Powerful! Isn't it?

No comments:

Post a Comment