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
0
votes
1 answer

How to adjust analysis timeout through UI

Is there a way to adjust the analysis timeout through the Code Contracts Editor Extension UI? If not, is there some other way to tweak this setting from within Visual Studio? I don't see any calls to cccheck in the .csproj file so I'm unclear on how…
Daniel
  • 47,404
  • 11
  • 101
  • 179
0
votes
0 answers

Code Contracts Invariant unproven.. Works fine with Contract.Assert at the end of each method

I'm hoping someone can help me.. I have a C# class in which I have implemented a Code Contracts invariant. My methods keep throwing "invariant unproven" errors unless I explicitly assert the invariant is true. My suspicion is that the problem…
krex
  • 345
  • 3
  • 8
  • 21
0
votes
1 answer

How can I turn on static Contract checking for the whole solution?

I am playing with Code Contracts, and the idea seems really nice. How can I however enable/disable different aspects of checking for the whole solution?
Grzenio
  • 35,875
  • 47
  • 158
  • 240
0
votes
1 answer

CodeContracts static checking says the members of an internal class of another assembly are not visible enough, despite using InternalVisibleTo

I'm writing a program in Visual Studio 2012, and I have a pair of classes in two separate projects: ProjectA: namespace Test { internal class A { private A(B b) { Contract.Requires(b.X != null); } } } ProjectB: namespace…
Philip C
  • 1,819
  • 28
  • 50
0
votes
1 answer

What is meant by 'visible' state change in the context of purity?

I have portable class library with ReflectionHelper class containing a handful set of convenient methods to perform reflection related operations. I marked many of these methods as pure but later in another peace of code I noticed a warning that…
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
0
votes
2 answers

Why does Contract.Assert throw an assertion dialog even when Runtime Checking is Off?

I have a number of Contract.Assert statements in my code. When in Debug Mode, the assertions that fail throw an assertion failed dialog. There are two things I don't understand about this: Are Contracts not controlled by the Rewiter? So I thought…
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
0
votes
0 answers

Why is this code not flagged as potentially violating the code contract?

Maybe I'm not grokking code contracts, but ISTM that this code: private static char GetBarcodeChecksumWithLegacyCode(string barcodeWithoutCzechSum) { Contract.Requires(!string.IsNullOrWhiteSpace(barcodeWithoutCzechSum)); …
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
0
votes
3 answers

Does including Contract.Assert have any effect on execution?

I have seen code which includes Contract.Assert like, Contract.Assert(t != null); Will using Contract.Assert have a negative impact on my production code?
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322
0
votes
1 answer

With Code Contracts, do I need to verify field/property initialization via `Ensures`?

using System.Diagnostics.Contracts; class C { public C(bool x) { Contract.Ensures(this.X == x); // is this necessary? this.X = x; } public readonly bool X; // could be a property instead, } …
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
0
votes
2 answers

Avoiding repetition in Interface contract classes

We want to use code contracts on our interfaces. We have a large interface hierarchy, leading to an awful lot of duplication in the contract classes. We have an interface IX which (through inheriting from other interfaces) has around 50 methods.…
Rob
  • 4,327
  • 6
  • 29
  • 55
0
votes
1 answer

Code Contracts Custom == Assertion Error

I am writing a simple 2d physics engine and I've overridden == for my Vector2 struct as follows: [Pure] public static bool operator ==(Vector2 v1, Vector2 v2) { Contract.Ensures(Contract.Result() == (v1.x == v2.x && v1.y == v2.y)); return…
Tom K.
  • 3
  • 4
0
votes
3 answers

Code Contracts and ccrewrite

Why should I allow ccrewrite to rewrite binaries if Code Contracts could make static check and be assure that all is correct? Is it normal to completely turn off ccrewrite?
EngineerSpock
  • 2,575
  • 4
  • 35
  • 57
0
votes
1 answer

CONTRACT_FULL is defined, but the definition is nowhere to be found

I am currently looking into the code contracts of the .NET framework. What I'd like to do is to use those contracts, while avoiding that my coworkers are forced to install the required extensions for Visual Studio and continue there work as is. Aber…
Nitram
  • 6,486
  • 2
  • 21
  • 32
0
votes
2 answers

Code Contracts for Windows Phone Device

I use Code Contracts in my code, my app runs fine on the emulator. When I deploy it on a device, it fails/crashes whenever Contract statement is executed. public static HTTPRequest CreateGetRequest(string url, …
ssk
  • 9,045
  • 26
  • 96
  • 169
0
votes
1 answer

Why is CodeContract warning about a null reference, when the ObjectInvariant checks it for null

Am trying to get up to speed with Code Contracts. Here is another issue that doesn't make sense to me: This is the Invariant: [ContractInvariantMethod] void Invariant() { Contract.Invariant(this._uiRoot.RowDefinitions!=null); …
Greg Gum
  • 33,478
  • 39
  • 162
  • 233