Wednesday, April 04, 2007

And/Or/Is Predicates

The .Net fx doesn't have any support to compose Predicates so I decided to create a Predicates helper for a small project I was working on the last weeks. Here you have my composite predicate methods:

    public static class Predicates
{
public static Predicate<T> And<T>(Predicate<T> predicate, Predicate<T> anotherPredicate)
{
return delegate(T t) { return predicate(t) && anotherPredicate(t); };
}

public static Predicate<T> Or<T>(Predicate<T> predicate, Predicate<T> anotherPredicate)
{
return delegate(T t) { return predicate(t) || anotherPredicate(t); };
}

public static bool Is<T>(object target, Predicate<T> predicate) where T : class
{
T targetAsT = target as T;
if ( null != targetAsT )
{
return predicate(targetAsT);
}
return false;
}

public static Predicate<T> GetNullPredicate<T>()
{
return delegate(T t) { return true; };
}
}

The Is<T> method allows you to validate if the target object is of T type before evaluating the predicate. This is something I found very useful when I am working with VS Automation Model because there are "Objects" that can implement many many interfaces so you have a collection of those objects that may or not target the T type. I will publish another post with a Finder example.

 

Labels:


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?