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

Generate Contracts for REST objects

I'm new to REST and this sounds like it should be pretty simple. In a .NET app, I can create a reference to a WCF service and the contracts for all the available types will be generated for me. Now I'm trying to consume a REST service in a Windows…
earthling
  • 5,084
  • 9
  • 46
  • 90
9
votes
2 answers

Microsoft Code Contracts without Visual Studio

This stack overflow question: Microsoft Code Contracts and CI build server asks how to get code contracts working on a build server without installing Visual Studio 2010. We're trying to do the same. We've followed the steps outlined in the…
Rob
  • 5,525
  • 1
  • 24
  • 26
9
votes
1 answer

How can I specify code contracts for existing framework (BCL) code?

Code contracts work great until you have to add a bazillion Contract.Assume(...) for the results coming out of framework code. For instance, MemoryStream.ToArray() never returns a null array, as best as I can tell from looking at it in Reflector,…
Sebastian Good
  • 6,310
  • 2
  • 33
  • 57
9
votes
2 answers

Collection Contracts and Threading

Suppose I have a custom collection class that provides some internal thread synchronization. For instance, a simplified Add method might look like this: public void Add(T item) { _lock.EnterWriteLock(); try { …
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
9
votes
1 answer

Why contract is malformed when using default(Type)?

When compiling code which uses code contracts, I have a very strange error I don't understand. [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant( this.isSubsidiary || this.parentCompanyId ==…
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
9
votes
3 answers

.net 4.0 Code Contracts. When to use? When are they a waste of time?

I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well at question regarding this. I still have never come across any sample code that uses code contracts so that gets me wondering.. is this really useful ? Or maybe its…
punkouter
  • 5,170
  • 15
  • 71
  • 116
9
votes
1 answer

Code Contracts: Invariants in abstract class

I have encountered a problem while using Invariants with Code Contracts. I want to define an Invariant within my abstract class but it is simply ignored. The code below shows my interface and the abstract…
Dynamike
  • 93
  • 4
9
votes
2 answers

How does Contract.Exists add value?

I am just starting to learn about the code contracts library that comes standard with VS2010. One thing I am running into right away is what some of the contract clauses really mean. For example, how are these two statements…
scobi
  • 14,252
  • 13
  • 80
  • 114
9
votes
2 answers

Code Contracts: Do we have to specify Contract.Requires(...) statements redundantly in delegating methods?

I'm intending to use the new .NET 4 Code Contracts feature for future development. This made me wonder if we have to specify equivalent Contract.Requires(...) statements redundantly in a chain of methods. I think a code example is worth a thousand…
herzmeister
  • 11,101
  • 2
  • 41
  • 51
9
votes
1 answer

Code Contracts with Interfaces: "Method Invocation skipped. Compiler will generate method invocation because the method is conditional... [...]"

Good evening, I just started playing with Microsoft.Contracts (latest version) and plugging it on top of a sample interface and right now it looks like this: namespace iRMA2.Core.Interfaces { using System; using System.Collections.Generic; …
Jörg Battermann
  • 4,044
  • 5
  • 42
  • 79
9
votes
2 answers

Nested contracts for generic interfaces

I can have a nested contracts type for a non-generic interface: [ContractClass(typeof(Foo.FooContracts))] public interface IFoo { string Bar(object obj); } But it complains when I try to do the same thing with a generic interface: …
Şafak Gür
  • 7,045
  • 5
  • 59
  • 96
9
votes
2 answers

Any alternatives to the .Net 4 Code Contracts static analyser?

It seems that the static analyser for use with the .NET 4.0 Code Contracts is only going to be available for Team Suite editions of Visual Studio - this puts it well outside the budget for my team. Are there any alternatives (open source, free or…
FinnNk
  • 3,249
  • 23
  • 25
9
votes
1 answer

C# code contracts - avoiding checking parameters for null references

I read today about C# 4.0 code contracts. It seems like the common practice for validating a parameter to a method isn't null is as follows: Contract.Requires(p != null); However it seems quite unreasonable to me that I'd have to do this for every…
user976850
  • 1,086
  • 3
  • 13
  • 25
9
votes
1 answer

Unproven Ensure that references another property in combination with an interface

Assume the following code: [ContractClass(typeof(ICC4Contract))] public interface ICC4 { bool IsFooSet { get; } string Foo { get; } } public class CC4 : ICC4 { private string _foo; public bool IsFooSet { get { return Foo != null; }…
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
9
votes
5 answers

Code Contracts in .NET 4.0, no joy for non-nullable reference types fans?

I've been playing with Code Contracts on VS2008 (http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx). They surely are nice and provide a solid alternative to if-then-throw checks inside methods. Nonetheless I've been hoping that they could…
RobSullivan
  • 651
  • 2
  • 7
  • 15