## Custom Constraints (NUnit 2.4 / 2.5)

You can implement your own custom constraints by creating a class that inherits from the Constraint abstract class, which supports performing a test on an actual value and generating appropriate messages. The class includes two abstract methods, which you must override and four virtual methods with default implementation that may be overridden as needed:

    public abstract class Constraint
    {
     	...
        public abstract bool Matches( object actual );
        public virtual bool Matches( ActualValueDelegate del );
        public virtual bool Matches<T>( ref T actual );
        public abstract void WriteDescriptionTo( MessageWriter writer );
        public virtual void WriteMessageTo( MessageWriter writer );
        public virtual void WriteActualValueTo( MessageWriter writer );
    	...
    }

Your derived class should save the actual argument to Matches in the protected field actual for later use.

The MessageWriter abstract class is implemented in the framework by TextMessageWriter. Examining the source for some of the builtin constraints should give you a good idea of how to use it if you have special formatting requirements for error messages.

### Custom Constraint Syntax

NUnit includes classes that implement a special constraint syntax, allowing you to write things like...

    Assert.That( myArray, Is.All.InRange(1,100) );

Of course, the NUnit constraint syntax will not be aware of your custom constraint unless you modify NUnit itself. As an alternative, you may use the Matches(Constraint) syntactic element in order to write code like...

    MyConstraint myConstraint = new MyConstraint();
    Assert.That( myArray, Has.Some.Matches(myConstraint) );