Questions tagged [code-contracts]

Code Contracts is a Microsoft open source project which allows you to express pre-conditions, post-conditions, and assertions directly in code.

Code Contracts is a Microsoft open source project, originating from Microsoft Research, which allows you to express pre-conditions, post-conditions, and assertions directly in code.

A check in a Code Contract is one that, if the code is correct, should always return true. In other words: it should not test whether the database is accessible or whether the user has entered an empty string -- those are outside factors. Code Contracts are there only to make sure your code is correct and maintains its invariants.

So, typically, you would do input parameter validation on public methods by explicitly checking the value and then throwing an exception if out of range. But for private methods -- which get called only by other code, and so can expect certain pre-conditions -- the input parameters can be checked with Code Contracts.

private void MyMethod(string machineId, int age)
{
    Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(machineId));
    Contract.Requires<ArgumentOutOfRangeException>(machineId.StartsWith("PEK"));
    Contract.Requires<ArgumentOutOfRangeException>(age > 16);
    //...
}

Post-conditions are expressions that must evaluate to true when the method is finished. A typical example is to verify that the output of a function is never null, or that it is within a certain range.

private string MachineNameOf(int id)
{
    Contract.Requires<ArgumentOutOfRangeException>(id > 100);
    Contract.Ensures(Contract.Result<string>() != null);
    //...
}

GitHub: https://github.com/Microsoft/CodeContracts

Tools at: http://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970.

See also (historical): http://research.microsoft.com/en-us/projects/contracts.

649 questions
17
votes
1 answer

Am I implementing this simple contract incorrectly?

This is my code: public class RegularPolygon { public int VertexCount; public double SideLength; public RegularPolygon(int vertexCount, double sideLength) { Contract.Requires(vertexCount >= 3); VertexCount =…
Nobody
  • 4,731
  • 7
  • 36
  • 65
16
votes
3 answers

Auto-implemented properties with non null guard clause?

I do agree with Mark Seeman's notion that Automatic Properties are somewhat evil as they break encapsulation. However I do like the concise syntax, readability and convenience they bring. I quote: public string Name { get; set; } The problem with…
Can Gencer
  • 8,822
  • 5
  • 33
  • 52
16
votes
1 answer

Is it bad to deploy code contracts into a production environment?

I am referencing this answer (emphasis mine): Have a look at the ContractClass and ContractClassFor attributes. This allows you to write classes with the code contracts in separate assemblies. This allows you to have the contracts available for dev…
user47589
15
votes
3 answers

Which should I use, CodeContract or CuttingEdge.Conditions?

I researched the use of a condition framework to verify data instead of if(cond) throw new SomeException(); SomeFramework.MakeSure(cond); In the end my choice is to use either the CodeContract or CuttingEdge.Conditions frameworks. I can not…
guyl
  • 2,158
  • 4
  • 32
  • 58
15
votes
5 answers

Can Extension Methods Be Called From The Immediate Window

I ask the question because whenever I attempt to call an extension method from the Immediate window in Visual Studio 2010 I get the following error: System.Collections.Generic.IEnumerable' does not contain a definition for 'ToList' and no…
Ɖiamond ǤeezeƦ
  • 3,223
  • 3
  • 28
  • 40
15
votes
4 answers

Programming by contracts in PHP

Programming by contracts is a modern trend in .NET, but what about libraries/frameworks for code contracts in PHP? What do you think about applicability of this paradigm for PHP? Googling for "code contracts php" gave nothing to me. Note: by "code…
zerkms
  • 249,484
  • 69
  • 436
  • 539
15
votes
2 answers

Contract that ensures the IEnumerable is not empty

The given code static public int Q() { return Enumerable.Range(0, 100) .Select(i => i) .First(); } emits the following warning: warning : CodeContracts: requires unproven: Any(source) If I remove .Select() clause it…
zerkms
  • 249,484
  • 69
  • 436
  • 539
15
votes
3 answers

So do C#4.0 Code Contracts Actually Do Anything?

After reading about the System.Diagnostics.Contracts.Contract static class that has been influenced by the awesomeness of Spec# I was thrilled and immediately started peppering my code with calls to Contract.Requires() and Contract.Ensures(). I…
George Mauer
  • 117,483
  • 131
  • 382
  • 612
15
votes
2 answers

How to (completely) uninstall Code Contracts Tool extension?

I'm trying to get rid of Code Contracts Tools extension on my system. I've uninstalled it from "programs and functionalities" yet it still appears as an installed extension inside Visual Studio. Any help would be appreciated.
Crono
  • 10,211
  • 6
  • 43
  • 75
15
votes
2 answers

how to install and use Code Contracts?

I have a basic question, might be it is so obvious but for some reason i can't seem to be successful with installing and using Code Contracts. I've downloaded the package from MSDN, installed it following the online documentation but i still get an…
NirMH
  • 4,769
  • 3
  • 44
  • 69
15
votes
4 answers

Code Contracts + Async in .NET 4.5: "The method or operation is not implemented"

I receive the following compilation error from ccrewrite when using Code Contracts 1.4.51019.0 in VS2012 on Windows 7 x64: "The method or operation is not implemented." It appears to be caused by a combination of property accessors and the use of…
Lawrence Wagerfield
  • 6,471
  • 5
  • 42
  • 84
14
votes
4 answers

JavaScript Code Contract Libraries?

I am just starting up a new web application and I want to implement some form of contract'esque style validation in my JavaScript. I did some quick googling, and came across JsContact but the syntax isn't quite what I had in mind. Is anyone aware of…
Chris Baxter
  • 16,083
  • 9
  • 51
  • 72
14
votes
1 answer

Code Contracts Vs. Object Initializers (.net 4.0)

At face value, it would seem that object initializers present a problem for .net 4.0 "code contracts", where normally the invariant should be established by the time the object constructor is finished. Presumably, however, object-initializers…
Brent Arias
  • 29,277
  • 40
  • 133
  • 234
13
votes
3 answers

Code contracts on auto-implemented properties

Is there any way to put contracts on automatically implemented properties in .NET? (And how if the answer is 'Yes')? (I assume using .NET code contracts from DevLabs)
wh1t3cat1k
  • 3,146
  • 6
  • 32
  • 38
13
votes
3 answers

Can I leave contracts in code that I'm merging with a codebase used by non-code contracts developers?

For the last few months I've been developing a side project for my company, but the higher-ups have now decided it would be a good fit in an existing product. I've been developing the side project using Microsoft's Code Contracts for static type…
Nick Udell
  • 2,420
  • 5
  • 44
  • 83