C# Predicates

The key word "predicate" is a shorthand way to refer to "a delegate which refers to methods having a single arguments and returning bool". Such a method is simply giving the answer to a true-false question about the argument.

It is defined as follows:

     public delegate bool Predicate(T Obj)

One place to use a predicate is as the second argument of the Find method of the Array class.

Example (from an MSDN web page):

using System;
using System.Drawing;

public class Example
{
   public static void Main()
   {
    int[] OurInts = { 12, 15, 73, -2, 67, 68, -99, -98, 0 };

    // Define the Predicate delegate.
    Predicate P = FindOdd;

    int FirstOdd = Array.Find(OurInts, P);

    // Display the first structure found.
    Console.WriteLine("First odd integer found:  {0}", FirstOdd);
   }

   private static bool FindOdd(int X)
   {
    return ( X % 2 != 0);
   }
}

Instead of looking for an odd integer, we could look for a negative integer, etc.

End of example

It is not unusual to provide a predicate in an argument list using "lambda syntax". The example above could be written using:

     int FirstOdd = Array.Find(OurInts, X => (X % 2 != 0));

Lambda expressions are a large separate topic.