SlideShare a Scribd company logo
Using the Code Contracts API for design-by-contract in .NETMelbourne Patterns Group PresentationBy Clarence Bakirtzidis(clarenceb@gmail.com)
AgendaOverviewUsing Code ContractsMain FeaturesRuntime Contract CheckingStatic Contract CheckingDemo(s)API ReferenceSummaryResourcesQuestions* DbC = Design-by-Contract2
OverviewWhat is the Code Contracts API?Library with Static Methods for DbCIt is a spin-off from the learnings of the Spec# projectObtaining and InstallingAcademic and Commercial LicensesTools ProvidedIntegration with Visual Studio3
OverviewWhat is Design-by-Contract?Originated from EiffelPreconditionCondition that is checked on entry to methodPostconditionCondition that is checked on exit of methodInvariant (constrain state of objects)Condition checked on exit of constructor and all public methods and propertiesStatic (Compile-time) and Runtime checking4
OverviewBenefits of Code ContractsRuntime Checking and Improved TestabilityStatic VerificationAPI DocumentationExamples5
Using Code Contracts.NET 4.0Part of the Base Class Library (BCL)No additional references required.NET 3.5 or earlierSeparate assembly Microsoft.Contracts.dllNeed to add reference to assembly in your projectsContract classes contains in:System.Diagnostics.Contracts namespaceCode Snippetsfor Visual Studioe.g. ci [TAB][TAB] => Contract.Requires(…)6
Using Code ContractsVisual Studio Project PropertiesRuntime Checking
Static Checking
Contract Reference AssemblyProject Properties7
Main FeaturesDesign-by-ContractRuntime CheckingStatic CheckingContract InheritanceSupports Abstract Methods and InterfacesGenerate API documentationHooks into XML documentation and inserts contract requirements (requires, ensures)8
Runtime Contract CheckingConfiguration optionsLevel of checkingOnly public surface contractsCall-site requiresCustom rewriter methodsAssembly rewriting via ccrewrite.exeInserts code in project assemblies to enforce contracts at runtime9
Static Contract CheckingConfiguration optionsNull valuesArray boundsArithmetic (div-by-zero)BaselineSuppress existing warnings in code base10
Demo(s)11Demo
API ReferencePreconditionsContract.Requires(…)EndContractBlock (“legacy-requires”)PostconditionsContract.Ensures(…)Contract.Ensures<E>(…)Contract.EnsuresOnThrow<E>(…)Prestate ValuesContract.Result<T>()Contract.OldValue<T>(…)OutParametersContract.ValueAtReturn<T>(…)InvariantsContract.Invariant(…)AttributesPureContractInvariantMethodContractVerificationContractPublicPropertyNameQuantifiersContract.ForAllContract.ExistsInterfacesandAbstractMethodsContractClassContractClassForOtherContract.Assert(…)Contract.Assume(…)ContractException12
SummaryCode Contracts bring DbC to the .NET frameworkProvides static and runtime checking of:PreconditionsPostconditionsObject invariantsExtends generated XML documentationSome known issues (still work in progress)Build slowdown - will be addressed in futureClosures - static checking does not work for closuresEdit-Continue does not work with code contract rewriting onNo contracts allowed on delegatesNo contracts on iterators that use “yield” as IL the code changed into different form (workaround exists for this)13
Code Contracts Summary14

More Related Content

What's hot (6)

PPTX
Automatic Test 2019-07-25
FedericoGuerinoni
 
PDF
Codemotion tech pills - Continuous performance
Bert Jan Schrijver
 
PDF
Amsterdam JUG - Continuous performance
Bert Jan Schrijver
 
PPTX
I++ unit testing
Gil Zilberfeld
 
PPTX
Get together on getting more out of typescript & angular 2
Ruben Haeck
 
PPTX
C# 6
Pascal Laurin
 
Automatic Test 2019-07-25
FedericoGuerinoni
 
Codemotion tech pills - Continuous performance
Bert Jan Schrijver
 
Amsterdam JUG - Continuous performance
Bert Jan Schrijver
 
I++ unit testing
Gil Zilberfeld
 
Get together on getting more out of typescript & angular 2
Ruben Haeck
 

Similar to Code Contracts API In .Net (20)

PPTX
Code Contracts API In .NET
Clarence Bakirtzidis
 
PPTX
Conformiq Tutorial
petersmagnusson
 
PPTX
Corba model ppt
Saransh Garg
 
PPTX
Workshop: .NET Code Contracts
Rainer Stropek
 
PPT
Tdd,Ioc
Antonio Radesca
 
PDF
Component Object Model (COM, DCOM, COM+)
Peter R. Egli
 
PPTX
WIndows Embedded Compact 2013 – What’s news
Mirco Vanini
 
PPTX
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
Will Huang
 
PDF
BizTalk Server Extensibility
BizTalk360
 
PPTX
Building a website with angular
Joseph Jorden
 
PPTX
Angular 9
Raja Vishnu
 
PPTX
OMG CORBA Component Model tutorial
Johnny Willemsen
 
PPT
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
ken.egozi
 
PDF
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Cisco Tech Blog
 
PDF
The Internal Architecture of Chrome Developer Tools
Miroslav Bajtoš
 
PPTX
How to Create a Service in Choreo
WSO2
 
PPTX
Enhance Your Code Quality with Code Contracts
Eran Stiller
 
PDF
How to create an Angular builder
Maurizio Vitale
 
PDF
Angular 2 kickstart
Geoffrey Filippi
 
Code Contracts API In .NET
Clarence Bakirtzidis
 
Conformiq Tutorial
petersmagnusson
 
Corba model ppt
Saransh Garg
 
Workshop: .NET Code Contracts
Rainer Stropek
 
Component Object Model (COM, DCOM, COM+)
Peter R. Egli
 
WIndows Embedded Compact 2013 – What’s news
Mirco Vanini
 
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
Will Huang
 
BizTalk Server Extensibility
BizTalk360
 
Building a website with angular
Joseph Jorden
 
Angular 9
Raja Vishnu
 
OMG CORBA Component Model tutorial
Johnny Willemsen
 
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
ken.egozi
 
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Cisco Tech Blog
 
The Internal Architecture of Chrome Developer Tools
Miroslav Bajtoš
 
How to Create a Service in Choreo
WSO2
 
Enhance Your Code Quality with Code Contracts
Eran Stiller
 
How to create an Angular builder
Maurizio Vitale
 
Angular 2 kickstart
Geoffrey Filippi
 
Ad

More from melbournepatterns (20)

PDF
An Introduction to
melbournepatterns
 
PPT
State Pattern from GoF
melbournepatterns
 
PDF
Iterator Pattern
melbournepatterns
 
PDF
Iterator
melbournepatterns
 
PPT
Concurrency Patterns
melbournepatterns
 
PPTX
Continuous Integration, Fast Builds and Flot
melbournepatterns
 
PPTX
Command Pattern
melbournepatterns
 
PPTX
LINQ/PLINQ
melbournepatterns
 
PDF
Gpu Cuda
melbournepatterns
 
PPTX
Facade Pattern
melbournepatterns
 
PPT
Phani Kumar - Decorator Pattern
melbournepatterns
 
PPT
Composite Pattern
melbournepatterns
 
PPT
Adapter Design Pattern
melbournepatterns
 
PPT
Prototype Design Pattern
melbournepatterns
 
PPT
Factory Method Design Pattern
melbournepatterns
 
PPT
Abstract Factory Design Pattern
melbournepatterns
 
PPT
A Little Lisp
melbournepatterns
 
PPT
State Pattern in Flex
melbournepatterns
 
PPT
Active Object
melbournepatterns
 
PPT
Extract Composite Talk Andy
melbournepatterns
 
An Introduction to
melbournepatterns
 
State Pattern from GoF
melbournepatterns
 
Iterator Pattern
melbournepatterns
 
Concurrency Patterns
melbournepatterns
 
Continuous Integration, Fast Builds and Flot
melbournepatterns
 
Command Pattern
melbournepatterns
 
LINQ/PLINQ
melbournepatterns
 
Facade Pattern
melbournepatterns
 
Phani Kumar - Decorator Pattern
melbournepatterns
 
Composite Pattern
melbournepatterns
 
Adapter Design Pattern
melbournepatterns
 
Prototype Design Pattern
melbournepatterns
 
Factory Method Design Pattern
melbournepatterns
 
Abstract Factory Design Pattern
melbournepatterns
 
A Little Lisp
melbournepatterns
 
State Pattern in Flex
melbournepatterns
 
Active Object
melbournepatterns
 
Extract Composite Talk Andy
melbournepatterns
 
Ad

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

Code Contracts API In .Net

Editor's Notes

  • #2: By Clarence Bakirtzidis ([email protected]) 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 namespaceThe 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 ContractsAcademic license version can be obtained from Microsoft Research siteCommercial license version can be obtained from DevLabs websiteStandard Edition (no static type checker) – any edition for Visual Studio except Express EditionIncludes 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 SystemSame as Standard Edition but also includes the Static checkerTools include:ccrewrite, for generating runtime checking from the contractscccheck, 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/86Pure object-oriented languageMajor feature is Design-by-contractSupports 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 runtimePrecondition - is a condition or predicate that must always be true just prior to the execution of some section of codePostcondtion - is a condition or predicate that must always be true just after the execution of some section of codeInvariant - 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.