Microsoft Code Contracts How to program Pre-conditions, Post-conditions, and Object Invariants Microsoft Code Contracts1
Specifying Object Invariants Annotate a method [ContractInvariantMethod] Inside the method you specify the object invariants [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(Salary >= 0); // Salary is a property Contract.Invariant(!String.IsNullOrEmpty(Name)); } If you write “hard” object invariants you may have to make an explicit constructor to initialize properties to legal values In case the default values are not legal Microsoft Code Contracts2
The class Contract Specifying pre- and post-conditions Namespace System.Diagnostics.Contracts us/library/system.diagnostics.contracts.contract(v=vs.110).aspx us/library/system.diagnostics.contracts.contract(v=vs.110).aspx Some interesting static methods Requires(Boolean expression) Used to specify pre-condition Comes in 4 variations With / without message With / without specific exception The default exception is ContractException. This exception is not public, so you cannot catch it! Normal exceptions are handy when you Unit test Ensures(Boolean expression) Used to specify post-condition Comes in 4 variations … (like Requires) EnsuresOnThrow (…) Microsoft Code Contracts3
Static vs. run-time analysis Static analysis Conditions and invariants are checked at compile-time Violations shown in Visual Studio (underlining) Run-time analysis Conditions and invariants are checked at run-time. Violations reported as messages or exceptions Microsoft Code Contracts4
Configuration: Plugin needed Code Contracts can be configured in many ways To do this you need a plugin for Visual Studio Code Contracts for.NET msdn.microsoft.com/1ec 7db c9-851f- 1ce455f msdn.microsoft.com/1ec 7db c9-851f- 1ce455f66970 In Visual studio right click a project and you’ll see an extra menu item “Code Contracts” Microsoft Code Contracts5
References and further readings Nagel et al. Professional C# 5.0 and.NET 4.5.1, Wrox 2014 Code Contracts, page Microsoft Research: Code Contracts MSDN Code Contracts MSDN Contract Class us/library/system.diagnostics.contracts.contract(v=vs.110).aspx us/library/system.diagnostics.contracts.contract(v=vs.110).aspx Code Contracts for.NET Plugin for Visual Studio 1ce455f ce455f66970 Microsoft Code Contracts6