SlideShare a Scribd company logo
Melbourne Patterns Group Presentation
By Clarence Bakirtzidis (clarenceb@gmail.com)
Agenda
 Overview
 Using Code Contracts
 Main Features
 Runtime Contract Checking
 Static Contract Checking
 Demo(s)
 API Reference
 Summary
 Resources
 Questions
* DbC = Design-by-Contract
2
Overview
 What is the Code Contracts API?
 Library with Static Methods for DbC
 It is a spin-off from the learnings of the
Spec# project
 Obtaining and Installing
 Academic and Commercial Licenses
 Tools Provided
 Integration with Visual Studio
3
Overview
 What is Design-by-Contract?
 Originated from Eiffel
 Precondition
○ Condition that is checked on entry to method
 Postcondition
○ Condition that is checked on exit of method
 Invariant (constrain state of objects)
○ Condition checked on exit of constructor and
all public methods and properties
 Static (Compile-time) and Runtime checking
4
Overview
 Benefits of Code Contracts
 Runtime Checking and Improved Testability
 Static Verification
 API Documentation
○ Examples
5
Using Code Contracts
 .NET 4.0
 Part of the Base Class Library (BCL)
 No additional references required
 .NET 3.5 or earlier
 Separate assembly Microsoft.Contracts.dll
 Need to add reference to assembly in your
projects
 Contract classes contains in:
 System.Diagnostics.Contracts namespace
 Code Snippets for Visual Studio
 e.g. ci [TAB][TAB] => Contract.Requires(…)
6
Using Code Contracts
Project Properties
Visual Studio Project Properties
• Runtime Checking
• Static Checking
• Contract Reference Assembly
7
Main Features
 Design-by-Contract
 Runtime Checking
 Static Checking
 Contract Inheritance
 Supports Abstract Methods and Interfaces
 Generate API documentation
 Hooks into XML documentation and inserts
contract requirements (requires, ensures)
8
Runtime Contract Checking
 Configuration options
 Level of checking
 Only public surface contracts
 Call-site requires
 Custom rewriter methods
 Assembly rewriting via ccrewrite.exe
 Inserts code in project assemblies to enforce
contracts at runtime
9
Static Contract Checking
 Configuration options
 Null values
 Array bounds
 Arithmetic (div-by-zero)
 Baseline
 Suppress existing warnings in code base
10
Demo(s)
11
Demo
API Reference
 Preconditions
 Contract.Requires(…)
 EndContractBlock (“legacy-
requires”)
 Postconditions
 Contract.Ensures(…)
 Contract.Ensures<E>(…)
 Contract.EnsuresOnThrow<E>(…)
 Prestate Values
 Contract.Result<T>()
 Contract.OldValue<T>(…)
 Out Parameters
 Contract.ValueAtReturn<T>(…)
 Invariants
 Contract.Invariant(…)
 Attributes
 Pure
 ContractInvariantMethod
 ContractVerification
 ContractPublicPropertyName
 Quantifiers
 Contract.ForAll
 Contract.Exists
 Interfaces and Abstract Methods
 ContractClass
 ContractClassFor
 Other
 Contract.Assert(…)
 Contract.Assume(…)
 ContractException
12
Summary
 Code Contracts bring DbC to the .NET framework
 Provides static and runtime checking of:
 Preconditions
 Postconditions
 Object invariants
 Extends generated XML documentation
 Some known issues (still work in progress)
 Build slowdown - will be addressed in future
 Closures - static checking does not work for closures
 Edit-Continue does not work with code contract rewriting
on
 No contracts allowed on delegates
 No contracts on iterators that use “yield” as IL the code
changed into different form (workaround exists for this)
13
Code Contracts Summary
14
Resources
 Code Contracts Project
 http://research.microsoft.com/en-
us/projects/contracts/
 MSDN Forum
 http://social.msdn.microsoft.com/Forums/en-
US/codecontracts/threads
 Spec# Project
 http://research.microsoft.com/en-
us/projects/specsharp
15
Questions
16

More Related Content

PPTX
Code Contracts API In .Net
PPTX
Design by Contract | Code Contracts in C# .NET
PPT
Design by contract
PPTX
Software quality with Code Contracts and PEX - CodeCamp16oct2010
PDF
SkładQA #3 - Contract Testing, M. Bryła
PDF
Use Geth to Access a Deployed Contract
PDF
Use Geth to Deploy Contract
PPTX
I++ unit testing
Code Contracts API In .Net
Design by Contract | Code Contracts in C# .NET
Design by contract
Software quality with Code Contracts and PEX - CodeCamp16oct2010
SkładQA #3 - Contract Testing, M. Bryła
Use Geth to Access a Deployed Contract
Use Geth to Deploy Contract
I++ unit testing

What's hot (8)

PPTX
Code Generation using T4
PPTX
Back-2-Basics: Exception & Event Instrumentation in .NET
PPTX
Why system verilog ?
PPTX
Rock Your Code With Code Contracts -2013
ODP
TDoc - Bringing Documentation to Tool
TXT
why c++11?
PDF
Odog : A Framework for Concurrent and Distributed software design
PDF
A tutorial on C++ Programming
Code Generation using T4
Back-2-Basics: Exception & Event Instrumentation in .NET
Why system verilog ?
Rock Your Code With Code Contracts -2013
TDoc - Bringing Documentation to Tool
why c++11?
Odog : A Framework for Concurrent and Distributed software design
A tutorial on C++ Programming
Ad

Similar to Code Contracts API In .NET (20)

PPTX
.NET 4.0 Code Contracts (2010)
PPTX
Enhance Your Code Quality with Code Contracts
PPTX
Code contracts by Dmytro Mindra
PPTX
Code Contracts
PPTX
Workshop: .NET Code Contracts
ODP
Introduction to Contracts and Functional Contracts
PPTX
Rock Your Code with Code Contracts
PPTX
Code contract
PDF
PDF
UContracts a DSL to document and validate structural requirements of frameworks
PDF
Contracts in Ruby - Vladyslav Hesal
PPTX
Back-2-Basics: Code Contracts
PDF
Beginning with wcf service
PPTX
Code contracts
PPTX
Lyntale: MS Code Contracts
PPTX
Next .NET and C#
PDF
apidays Australia 2022 - Schemas are not contracts!, Matt Fellows, Pactflow
PDF
Automated Developer Testing: Achievements and Challenges
PPTX
Dynamic C#
PPT
Contract First Modeling Services Using Uml
.NET 4.0 Code Contracts (2010)
Enhance Your Code Quality with Code Contracts
Code contracts by Dmytro Mindra
Code Contracts
Workshop: .NET Code Contracts
Introduction to Contracts and Functional Contracts
Rock Your Code with Code Contracts
Code contract
UContracts a DSL to document and validate structural requirements of frameworks
Contracts in Ruby - Vladyslav Hesal
Back-2-Basics: Code Contracts
Beginning with wcf service
Code contracts
Lyntale: MS Code Contracts
Next .NET and C#
apidays Australia 2022 - Schemas are not contracts!, Matt Fellows, Pactflow
Automated Developer Testing: Achievements and Challenges
Dynamic C#
Contract First Modeling Services Using Uml
Ad

Recently uploaded (20)

PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
AI in Product Development-omnex systems
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Introduction to Artificial Intelligence
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
history of c programming in notes for students .pptx
PDF
System and Network Administration Chapter 2
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
ai tools demonstartion for schools and inter college
Odoo POS Development Services by CandidRoot Solutions
Odoo Companies in India – Driving Business Transformation.pdf
AI in Product Development-omnex systems
ISO 45001 Occupational Health and Safety Management System
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Wondershare Filmora 15 Crack With Activation Key [2025
Introduction to Artificial Intelligence
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PTS Company Brochure 2025 (1).pdf.......
ManageIQ - Sprint 268 Review - Slide Deck
How to Migrate SBCGlobal Email to Yahoo Easily
history of c programming in notes for students .pptx
System and Network Administration Chapter 2
2025 Textile ERP Trends: SAP, Odoo & Oracle
Navsoft: AI-Powered Business Solutions & Custom Software Development
Online Work Permit System for Fast Permit Processing
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
ai tools demonstartion for schools and inter college

Code Contracts API In .NET

  • 1. Melbourne Patterns Group Presentation By Clarence Bakirtzidis (clarenceb@gmail.com)
  • 2. Agenda  Overview  Using Code Contracts  Main Features  Runtime Contract Checking  Static Contract Checking  Demo(s)  API Reference  Summary  Resources  Questions * DbC = Design-by-Contract 2
  • 3. Overview  What is the Code Contracts API?  Library with Static Methods for DbC  It is a spin-off from the learnings of the Spec# project  Obtaining and Installing  Academic and Commercial Licenses  Tools Provided  Integration with Visual Studio 3
  • 4. Overview  What is Design-by-Contract?  Originated from Eiffel  Precondition ○ Condition that is checked on entry to method  Postcondition ○ Condition that is checked on exit of method  Invariant (constrain state of objects) ○ Condition checked on exit of constructor and all public methods and properties  Static (Compile-time) and Runtime checking 4
  • 5. Overview  Benefits of Code Contracts  Runtime Checking and Improved Testability  Static Verification  API Documentation ○ Examples 5
  • 6. Using Code Contracts  .NET 4.0  Part of the Base Class Library (BCL)  No additional references required  .NET 3.5 or earlier  Separate assembly Microsoft.Contracts.dll  Need to add reference to assembly in your projects  Contract classes contains in:  System.Diagnostics.Contracts namespace  Code Snippets for Visual Studio  e.g. ci [TAB][TAB] => Contract.Requires(…) 6
  • 7. Using Code Contracts Project Properties Visual Studio Project Properties • Runtime Checking • Static Checking • Contract Reference Assembly 7
  • 8. Main Features  Design-by-Contract  Runtime Checking  Static Checking  Contract Inheritance  Supports Abstract Methods and Interfaces  Generate API documentation  Hooks into XML documentation and inserts contract requirements (requires, ensures) 8
  • 9. Runtime Contract Checking  Configuration options  Level of checking  Only public surface contracts  Call-site requires  Custom rewriter methods  Assembly rewriting via ccrewrite.exe  Inserts code in project assemblies to enforce contracts at runtime 9
  • 10. Static Contract Checking  Configuration options  Null values  Array bounds  Arithmetic (div-by-zero)  Baseline  Suppress existing warnings in code base 10
  • 12. API Reference  Preconditions  Contract.Requires(…)  EndContractBlock (“legacy- requires”)  Postconditions  Contract.Ensures(…)  Contract.Ensures<E>(…)  Contract.EnsuresOnThrow<E>(…)  Prestate Values  Contract.Result<T>()  Contract.OldValue<T>(…)  Out Parameters  Contract.ValueAtReturn<T>(…)  Invariants  Contract.Invariant(…)  Attributes  Pure  ContractInvariantMethod  ContractVerification  ContractPublicPropertyName  Quantifiers  Contract.ForAll  Contract.Exists  Interfaces and Abstract Methods  ContractClass  ContractClassFor  Other  Contract.Assert(…)  Contract.Assume(…)  ContractException 12
  • 13. Summary  Code Contracts bring DbC to the .NET framework  Provides static and runtime checking of:  Preconditions  Postconditions  Object invariants  Extends generated XML documentation  Some known issues (still work in progress)  Build slowdown - will be addressed in future  Closures - static checking does not work for closures  Edit-Continue does not work with code contract rewriting on  No contracts allowed on delegates  No contracts on iterators that use “yield” as IL the code changed into different form (workaround exists for this) 13
  • 15. Resources  Code Contracts Project  http://research.microsoft.com/en- us/projects/contracts/  MSDN Forum  http://social.msdn.microsoft.com/Forums/en- US/codecontracts/threads  Spec# Project  http://research.microsoft.com/en- us/projects/specsharp 15

Editor's Notes

  • #2: By Clarence Bakirtzidis (clarenceb@gmail.com) for Melbourne Patterns Group on 02/12/2009.
  • #4: What is Code Contracts API? (From Microsoft Research) "Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation."  Library consists of a set of static methods in the System.Diagnostics.Contract namespace The use of a library has the advantage that all .NET languages can immediately take advantage of contracts immediately. Spec# is a Microsoft Research project which extends the C# language with constructs for non-null types, preconditions, postconditions, and object invariants. It is a more advanced research project than Code Contracts Academic license version can be obtained from Microsoft Research site Commercial license version can be obtained from DevLabs website Standard Edition (no static type checker) – any edition for Visual Studio except Express Edition Includes the stand-alone contract library, the binary rewriter (for runtime checking), the reference assembly generator, and a set of reference assemblies for the .NET Framework. VSTS Edition (includes static type checker) – Only for Visual Studio Team System Same as Standard Edition but also includes the Static checker Tools include: ccrewrite, for generating runtime checking from the contracts cccheck, a static checker that verifies contracts at compile-time. ccdoc,  a tool that adds contracts to the XML documentation files and to Sandcastle-generated MSDN-style help files. Plan is to add further tools. There is a prototype for a VS 2010 add-in so that inherited contracts show up as you type. Integration includes properties tab called “Code Contracts” for VS projects (can enable/disable various features)
  • #5: Eiffel was created by Bertrand Meyer in 1985/86 Pure object-oriented language Major feature is Design-by-contract Supports preconditions, postconditions, invariants, loop invariants, loop variants (ensure loop will end), check (like C assert) Can choose to enable only preconditions (e.g. for 3pp code) to reduce contract checking "void safety" - void is null in Eiffel.  e.g. x.f where x is null the compiler can detect if this will succeed at runtime Precondition - is a condition or predicate that must always be true just prior to the execution of some section of code Postcondtion - is a condition or predicate that must always be true just after the execution of some section of code Invariant - invariants constrain the state stored in the object.  Methods of the class should preserve the invariant. Class invariants are established during construction and constantly maintained between calls to public methods. Temporary breaking of class invariance between private method calls is possible, although not encouraged.
  • #6: Runtime Checking and Improved Testability Binary rewriter (ccrewriter.exe) modifies a program by injecting the contracts, which are checked as part of program execution. Each contract acts as an oracle, giving a test run a pass/fail indication (oracle:- mechanism used for determining whether a test has been passed or failed, e.g. Assert.True) Automatic testing tools, such as Pex, can take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions. Static Verification Static checker can determine if there are any contract errors without running the program (and all violations rather than just a particular executed path as with runtime) No foolproof. Sometimes the checker gets confused and cannot prove contracts are satisfied (e.g. when preconditions rely on existing state of the object, e.g. amout < balance). Can assist static check by using Contract.Assert and Contract.Assume Checks for implicit contracts, such as null dereferences and array bounds, as well as the explicit contracts API Documentation Document generator (ccdoc.exe) augments the existing XML doc files with contract information. Documentation is now kept up to date from code (no need to maintain pre/postconditions, invariants manually in XML comments) Also includes new stylesheets for Sandcastle so that generated documentation pages have contract sections.
  • #7: Code Contracts will ship bundled with .NET 4.0.  (Static Type Checker will be available with VS2010 Ultimate only)
  • #8: Contract Reference Assembly Without building a contract reference assembly, other projects cannot determine what contracts are present.
  • #9: Static Checking By default tries to prove explicit contract checks (on build): Assertions, invariants, requires, ensures, inherited ensures, requires methods in referenced assemblies, object invariants on classes extending base classes and interfaces in other assemblies Runtime Checking Contract rewriter places runtime checks in the assemblies at appropriate places Contract Inheritance Code contracts support behavioural subtyping where contracts are enforced in subtypes of the parent type where the contracts are defined. Subtypes cannot add any preconditions as this may further constrain the contract (and MS see no practical use for weakening the contract). If supertype does not declare any preconditions then the subtype is still not allowed to add any Method preconditions must be declared on the root method of an inheritance/implementation chain, i.e., the first virtual or abstract method declaration, or the interface method itself. Postconditions can be added in subtypes (adding further postconditions gives client more guarantees than before).  They are effectively conjoined ("and"-ed) with the supertype postconditions Object invariants are also inherited.  They are enforced on the type they were declared on and any subtypes. Base class invariants are enforced at runtime automatically provided the assembly containing the base class has contract runtime checking enabled.  Therefore, do not invokes the base class object invariant from your code.
  • #10: Level of checking Explain the API and "perfect world" scenarios where everything is enabled for run-time and release builds Then explain why you might want to disable checking in release builds and what options you have (e.g. legacy requires, contract assemblies) Contract Rewriting The contract rewriter performs several tasks: postconditions are moved to the end of the method body method return values are substituted for occurrences of Contract. Result<T>() pre-state values are sub- stituted for occurrences of Contract.OldValue<T>(). In addition, contract inheritance is performed.
  • #12: Use “Binary Search” demo from Code Contracts samples as a basis for discussing static checking behaviour Explain array bound, null, arithmetic (div-by-zero) checking Time permitting, “Chunker” is also a good example for object invariants and static checking
  • #13: Can use System.Linq.Enumerable.All instead of Contract.ForAll in Pre and Postconditions. Can use System.Ling.Enumerable.Any instead of Contract.Exists in Pre and Postconditions. ContractException Is not a public type but written into each assembly as a nested private type and thus cannot be caught by your code (you shouldn't be writing code to catch contract exceptions!)
  • #14: Why not just use Debug.Asserts instead of Contract.Requires, etc? Preconditions should establish conditions for caller prior to calling method and hence should only refer to state visible to caller. Debug.Asserts can be use to refer to internal consistency. Postconditions: usnig Debug.Assert everywhere the method can exit is error prone and tedious. With contracts you specify the postcondition once at the start of the method. Contracts can be inherited and avoid repeating checks over and over in subtypes. Contracts can be used to generate API documentation [Extracted from the Microsoft Code Contracts FAQ]
  • #17: Credits: Cube image is from http://lostmitten.org/