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

Why code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#?

Why code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#? In the CLR via C# book I met the following excerpt: And since a contract cannot be made stricter with new versions (without…
qqqqqqq
  • 1,831
  • 1
  • 18
  • 48
0
votes
1 answer

how to remove Microsoft.CodeContracts reference from a solution?

A have a large web service solution (written in C# targetting .NET 3.5) which is comprised of 16 individual projects (many class libraries, a few web applications and setup projects). It is developed in visual studio 2010. I was recently…
MattDavey
  • 8,897
  • 3
  • 31
  • 54
0
votes
1 answer

Issues with Contract.Requires() and loop invariant

I am following the codecontracts tutorial (https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts#usage-guidelines) and I seem to have trouble getting the simplest thing working. Given the method definition public int…
0
votes
2 answers

How does dot net core process Arg.NotNull and Contract.Requires assets

In the aspnet-api-versioning I have found out a codeblock: DefaultApiControllerFilter( IEnumerable pecifications ) { Arg.NotNull( specifications, nameof( specifications ) ); …
Stadub Dima
  • 858
  • 10
  • 24
0
votes
1 answer

When building solution, ccrewrite fails with rewrite aborted due to metadata errors -> could not resolve type reference, fails on my machine only

I am having a really strange issue, when I try to build solution it fails The command ""(solution)\packages\DotNet.Contracts.1.10.20606.1\Bin\ccrewrite.exe" "@(project)ccrewrite.rsp"" exited with code -1. When I set detailed build output, I get…
Prokurors
  • 2,458
  • 3
  • 40
  • 65
0
votes
2 answers

Comparing integers in contracts

I am creating a small application based on code contracts, is there a way to write a specification, which would kinda work in rock, paper, scissors way? I'd like to make a specification, which would follow something like this: 0- rock 1- paper 2-…
user10485093
0
votes
2 answers

Code Contract gives null warning with ServiceLocator

Using HtmlPage.RegisterScriptableObject("Shell", serviceLocator.GetInstance()); gives me a null warning. How can I make this go away?
0
votes
2 answers

Code contracts static checking not working correctly?

I made a class with a code contract in the constructor CodeTypes has a list of string properties. Contract.Requires(type == CodeTypes.AdmitDx1 || type == CodeTypes.AdmitDx2 || type == CodeTypes.AdmitDx3 || type == CodeTypes.DX || type ==…
Xander
  • 9,069
  • 14
  • 70
  • 129
0
votes
1 answer

Code Contracts failing example Graph.Remove(Edge e)

Here's a simple graph manipulation method which I have decorated with Code Contracts. The ensures claim won't prove but I can't see why! I believe it claims that after calling Remove(), either the edge is no longer in the edges list OR the result…
Jason Kleban
  • 20,024
  • 18
  • 75
  • 125
0
votes
1 answer

CodeContracts: Possibly calling a method on a null reference 'this.Master'

If I have a basic master page and content page and I want to use some property or method of the master page from the content page, such as: string something = this.Master.MasterPageFile; Code Contracts static analysis will complain with: warning :…
Richard
  • 5,810
  • 6
  • 29
  • 36
0
votes
1 answer

Contract Ensures unproven for GUID

I m having a ensures unproven: !ReferenceEquals(Contract.Result(), null) that contract is on an interface I have no control of my implementation is something like this public Guid Blah() { var guid = Guid.NewGuid(); …
roundcrisis
  • 17,276
  • 14
  • 60
  • 92
0
votes
2 answers

Contract.Ensures unproven in Multiple object / class chain Code Contracts

I have the following class structure: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; namespace contractsTest { class Program { static void Main(string[]…
Bogdan Maxim
  • 5,866
  • 3
  • 23
  • 34
0
votes
1 answer

Code Contracts on different projects

I have a project with contracts (project A) that generates a library and another one (project B) that implements an interface from that library. I've tried copying the contract files from project A to project B and the contracts fire at runtime…
boromak
  • 351
  • 3
  • 11
0
votes
1 answer

Contract.Ensures Malformed contract section in method

Why am I getting this building error "Malformed contract section in method..." on the following code? List MatrizesCorrelacao; public string lsMatrizes { get { if (TudoDataUnica == true) { …
0
votes
2 answers

How can I check a post-condition for a field's old value in D?

In C# I could use Contract.OldValue in a post-condition to check how a field has changed. How can I do this in D? I've read the relevant page in the documentation, but it doesn't mention this. Specifically, I'm writing a page renderer and am…
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93