Invariants are special contracts that ensure an object is considered valid during all its lifetime. Invariant contracts are provided inside one method decorated with the ContractInvariantMethod
attribute that affects all members in the enclosing class. Only one invariant method can be declared inside a class, and typically it should be marked as Protected
to avoid risk of calls from clients. The method is by convention named ObjectInvariant
(although not mandatory) and is used instead of preconditions and postconditions. The following code snippet provides an example:
Simply this code establishes that during the entire lifetime of the Rectangle
object, both Width
and Height
properties must be greater than zero so that they can be considered in a valid state.
3.145.177.115