Skip to content
Craig Fowler edited this page Mar 5, 2020 · 2 revisions

There are a few other pieces of functionality provided in this library.

Dynamic Specifications

The most reusable way to create specifications is by writing classes which implement either ISpecificationExpression<T> or ISpecificationFunction<T>. If an ad-hoc specification object is required then they may be created using the Spec static class:

// Spec.Expr<T> creates a specification expression
var overSix = Spec.Expr<int>(x => x > 6);

// Spec.Func<T> creates a specification function
var isEven = Spec.Func<int>(x => {
    if(x % 2 == 0) return true;
    return false;
});

Note: This example of a specification function could be refactored to be an expression.

Getting predicate delegates

Any specification (expression or function) may be converted to an instance of Predicate<T>. This is provided by the AsPredicate() extension method.

Converting specification expressions to functions

Although there would seem to be very little benefit in normal circumstances, it is possible to convert a specification to a specification function. Specification expressions have an extension method AsSpecificationFunction() allowing just that.

The Predicate static class

The static class Predicate, in the namespace CSF, provides some utility functionality to work with Linq expressions. These are not specification expressions but System.Linq.Expressions.Expression<Func<T,bool>> objects.

The functionality available there is:

  • True<T> returns an expression which always evaluates to true
  • False<T> returns an expression which always evaluates to false
  • Create<T> is a convenience for creating expressions without excessive casting
  • And<T> composes two expressions using a logical AND
  • Or<T> composes two expressions using a logical OR
  • Not<T> negates an expression; a logical NOT
  • Compose<T> allows custom composition of two expressions, using a custom composition function

Note that the composition functions in this class use an ORM-safe mechanism of parameter-rebinding. This should mean that composed expressions are safe to use in ORMs such as NHibernate or Entity Framework.