This project is read-only.

Required vs Optional

Required

The Required statement will assert the value of the property or expression is a value other than NULL or the default value for the type. If the assertion fails, a required error message is generated, and any remaining rules will be ignored. The the assertion is true, then all additional rules are evaluated.

Optional

The Optional statement will assert the value of the property or expression is a value other than NULL or the default value for the type. If the assertion fails, no error messages will be generated, any remaining rules will be ignored.

Key Differences

Design

The design of Required vs. Optional allows the specification to quickly short-circuit rules if a value was not supplied.

Determining if a value was supplied

String

String.Empty or Null

Value Types

Default Values Table (C# Reference)
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
default(T)

Object

Null

IEnumerable

Null or Empty Collection

Special Note on Int's

The default value of an integer is 0. If a property is marked as Required and the value was explicitly set to 0, it will fail required. Setting 0 is the same as int i = new int(); If 0 is a legitimate value for your business rule, then mark it as Optional.

Bypassing Optional and Required

In the rare case that Required will not work with your business rules, you can use an expression for the object the property is on in conjunction with Optional and Expect to enforce your rules. For example

//String Null not allowed by String.Empty is
Check( c=> c, "Last Name").Optional().Expect( (c, contact) => contact.LastName != null);

Last edited May 24, 2010 at 10:30 PM by TechnoAg, version 2

Comments

No comments yet.