And Constraint
AndConstraint combines two constraints and succeeds only if both succeed.
Usage
<constraint>.And.<constraint>
Examples
[Test]
public void AndConstraint_Examples()
{
int value = 42;
// Both conditions must be true
Assert.That(value, Is.GreaterThan(0).And.LessThan(100));
Assert.That(value, Is.Positive.And.LessThanOrEqualTo(50).Or.GreaterThanOrEqualTo(40));
// String constraints
Assert.That("Hello World", Does.StartWith("Hello").And.EndWith("World"));
Assert.That("test@example.com", Does.Contain("@").And.EndWith(".com"));
// Null checking pattern (check null first!)
int? nullable = 42;
Assert.That(nullable, Is.Not.Null.And.GreaterThan(0));
// Collection constraints
Assert.That(new[] { 1, 2, 3 }, Is.Not.Empty.And.All.Positive);
}
Evaluation Order and Precedence
Constraints are evaluated left to right. This is important for null checks:
[Test]
public void AndConstraint_NullCheck_Examples()
{
int? value = 42;
// CORRECT: Check null first - fails gracefully with message for null
Assert.That(value, Is.Not.Null.And.GreaterThan(9));
}
Note
Or has higher precedence than And. The expression A.And.B.Or.C is evaluated as A.And.(B.Or.C).
See Also
- Or Constraint - Either condition must be true
- Not Constraint - Negate a constraint