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
7
votes
2 answers

Code Contracts warn of "ensures unproven" when locks are involved

I'm trying to work out how .NET Code Contracts interact with the lock keyword, using the following example: public class TestClass { private object o1 = new object(); private object o2 = new object(); private void Test() { …
Philip C
  • 1,819
  • 28
  • 50
7
votes
2 answers

Can Microsoft Code Contracts be used with an ASP.NET Website?

I'm currently using Microsoft Code Contracts in an ASP.NET MVC application without any issues but I can not seem to get it quite running in a basic ASP.NET Web site. I'm not entirely sure it was made to work with this type of project (although it…
jamesmillerio
  • 3,154
  • 4
  • 27
  • 32
7
votes
5 answers

Bug in iterators with code contracts?

The following code fails on the pre condition. Is this a bug in code contracts? static class Program { static void Main() { foreach (var s in Test(3)) { Console.WriteLine(s); } } static…
pn.
  • 852
  • 1
  • 8
  • 9
6
votes
4 answers

Is it possible to specify code contracts to ensure that method doesn't change state of object

Lets say I got a boolean IsValid property on my object. I would like to create a method, and ensure that IsValid isn't changed after calling it, whether it was true or false before the call. Is there a support for such thing?
Valentin Kuzub
  • 11,703
  • 7
  • 56
  • 93
6
votes
3 answers

CodeContracts with collection types

I have a collection of child items in my class and I have a public accessor to it. I want to provide a postcondition to ensure that items in the collection are not null (I know, that in tests 2 and 3 caller can change the collection, but for now my…
nevermind
  • 2,300
  • 1
  • 20
  • 36
6
votes
2 answers

Code Contracts: Ensures Unproven & Requires Unproven

I'm not sure if I'm doing something wrong here or if it needs to be fixed... I have a custom Dictionary wrapper class and here is a snippet of the code that is necessary. public int Count { get { …
michael
  • 14,844
  • 28
  • 89
  • 177
6
votes
1 answer

Why does Code Contracts shows "Malformed contract. Found Requires after assignment" in method with params keywork?

I've been troubleshooting with this error for hours and I can't seem to understand why this happens. Consider the following code: using System; using System.Diagnostics.Contracts; using System.Linq.Expressions; namespace Contracts { class Data …
Marco
  • 5,555
  • 2
  • 17
  • 23
6
votes
2 answers

Make Contract.Assert throw an exception rather than display a Dialog box

If I'm using the new Code Contracts Contract.Assert method, is it possible to make it throw an exception rather than display a dialog box? I want to do this when running unit tests on the build machine.
Nick Randell
  • 17,805
  • 18
  • 59
  • 74
6
votes
2 answers

Code contracts warnings when implementing ICollection with backing collection

I've got this code: public class MyCollection : ICollection { private readonly ICollection _inner = new Collection(); public void Add(string item) { _inner.Add(item); } // <-- CodeContracts: ensures…
Allrameest
  • 4,364
  • 2
  • 34
  • 50
6
votes
3 answers

Unit testing code contracts

I'm just having a play with the code contracts in .Net 4.0 and must be missing something obvious as they are not behaving as I would expect. I have always used a simple if... then.. throw statement to perform any validation at the start of a…
fluent
  • 2,393
  • 4
  • 22
  • 32
6
votes
1 answer

Should Code Contracts be used for security?

Are there any reasons why you wouldn't use Code Contracts to enforce business rules? Imagine you have a User class that represents a single user of a system and defines actions that can be performed against other users. You could write a…
Richard Poole
  • 3,946
  • 23
  • 29
6
votes
2 answers

Why is this string-based Contract.Ensure call unproven?

I have the following code in my .Net 4 app: static void Main(string[] args) { Func(); } static string S = "1"; static void Func() { Contract.Ensures(S != Contract.OldValue(S)); S = S + "1"; } This givens me an ensures unproven warning…
6
votes
3 answers

Is it possible to violate Liskov Substitution Principle in a constructor?

I've just installed Microsoft Code Contracts. It's a part of .NET Framework and Visual Studio add-on. It provides runtime checking and static checking of defined contracts. The tool has four warning levels so I set up the highest. I've declared…
6
votes
3 answers

Is there a way not to let MsBuild run static contract analysis with code contracts?

In my project, static checking is disabled, but still, when I run msbuild.exe with cmd, it starts static checking for each project... Is there a way, with parameters, to disable this?
Lieven Cardoen
  • 25,140
  • 52
  • 153
  • 244
6
votes
2 answers

Why does Code Contracts claim that "Ensures is false" for this code?

This is a constructor in one of my classes: public SemanticVersion(string version) { Contract.Requires(!string.IsNullOrEmpty(version)); Contract.Ensures(MajorVersion >= 0); Contract.Ensures(MinorVersion >= 0); …
Tim Long
  • 13,508
  • 19
  • 79
  • 147