C# Coding Solutions—Predicate Functor

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

C# Coding Solutions

© 2006 Christian Gross

The Predicate Functor

Predicate functors are similar in some ways to comparer functors when testing an object for a go or no-go condition. The difference with predicate functors is that they return either a true or false value. A predicate functor tests an object to see if it meets certain conditions.

The following is the definition of the delegate for the predicator functor:

public delegate bool DelegatePredicate< type>( type input);

DelegatePredicate uses Generics to define the type that will be tested, and has a single parameter. An implementation performs some operations on the type, and returns either a true or false value.

Unlike other functors, predicate functors are usually chained together (using Boolean operators such as and, or, and not) to perform more-sophisticated tests. Consider the following Boolean and functor implementation:

public class PredicateAndFunctor< type> {
    DelegatePredicate<type> _predicates;
    public PredicateAndFunctor( 
      DelegatePredicate<type>[] functors) {
        foreach( 
          DelegatePredicate< type> functor in functors) {
            _predicates += functor;
        }
    }
 
    private bool PredicateFunction( type obj) {
        foreach( 
          Delegate delg in _predicates.GetInvocationList()) {
            if( !delg( obj)) {
                return false;
            }
        }
        return true;
    }
    static DelegatePredicate< type> CreateInstance(
        DelegatePredicate< type>[] functors) {
        return new DelegatePredicate< type>(
            new PredicateAndFunctor< type>(
                 functors).PredicateFunction);
    }
}

The class PredicateAndFunctor<> has a private data member, _predicates, which represents an array of child predicates that will be chained together using the and (&&) operator. If any of the child predicates return a false, then PredicateAndFunctor<> will return false. The method PredicateFunction is the delegate implementation that iterates and calls in successive fashion the delegates contained within the _predicates data member.

In the example of creating the flight comparer delegate, an anonymous method was used. Because PredicateAndFunctor<> has state, a class instance is needed and the static method CreateInstance is used to instantiate the type; that, in turn, creates the delegate DelegatePredicate.


Previous_Page_.gif Next_Page_.gif


Personal tools