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

How does Contract.Ensures work?

I'm starting to use Code Contracts, and whilst Contract.Requires is pretty straight forward, I'm having trouble seeing what Ensures actually does. I've tried creating a simple method like this: static void Main() { DoSomething(); } private…
Steffen
  • 13,648
  • 7
  • 57
  • 67
20
votes
2 answers

Building with Code Contracts?

I have the following method: private void DoSomething(CoolClass coolClass) { if (coolClass == null) { throw new ArgumentNullException("coolClass"); } coolClass.Name = "Pepe"; } With Code Contracts we can write it like…
elranu
  • 2,292
  • 6
  • 31
  • 55
20
votes
2 answers

Code Contracts doesn't seem to work on VS2012

I'm reading up on Code Contracts, which at first glance seem to be pretty revolutionary, but I can't seem to get them working. I'm running Windows 8 and Visual Studio 2012 Premium (Release versions of both). I then installed Code Contracts from…
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
20
votes
2 answers

Code Contracts + Code Analysis

I think about starting to use Code Contracts in my code base. I already use Code Analysis with all rules enabled and a goal of zero warnings. However, when using Contract.Requires(parameter != null) I get a warning from Code Analysis, namely…
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
19
votes
4 answers

Code Contracts at runtime

As far as I read in a nutshell book, code contracts could degrade the runtime performance. Is it possible to disable code contracts in production?
DarthVader
  • 52,984
  • 76
  • 209
  • 300
19
votes
2 answers

When should one use Code contracts that comes with C# 4.0?

I was going through a question on SO which was about new features of c# 4.0 and jon skeet's answer had Code Contracts feature of C# 4.0.. But i really cant understand when to use them.. Any suggestion...
ACP
  • 34,682
  • 100
  • 231
  • 371
19
votes
2 answers

Automatic documentation/contract generation for Pub/Sub RabbitMQ

In the REST world, we have something like a Swagger Specification, which fully describes the contract over a REST interface boundary (between client and server). Those Swagger specifications can be used to auto-generate REST clients, but also to…
Boeboe
  • 2,070
  • 1
  • 17
  • 21
19
votes
7 answers

.NET Guard Class Library?

I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal…
Brian Vallelunga
  • 9,869
  • 15
  • 60
  • 87
19
votes
2 answers

Throwing an exception vs Contract.Requires?

I'm wondering whether should I throw exceptions or call Contract.Requires For example: public static void Function(String str) { if (str == null) throw new ArgumentNullException("str", "Input string cannot be null."); //…
MasterMastic
  • 20,711
  • 12
  • 68
  • 90
18
votes
3 answers

What is the best alternative for Code Contracts in Visual Studio 2015?

I am looking to validate method parameters in my code, in the most elegant fashion possible. Code Contracts don't seem to work in 2015. Does anyone use any alternatives?
user1654348
  • 283
  • 4
  • 12
18
votes
1 answer

Purpose of PureAttribute on parameter

I understand that the PureAttribute is used to mark something (class, method, delegate etc.) as making no visible changes, but I can see from the following definition that it can be applied to method…
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
18
votes
5 answers

Abstract class instantiation in 'C# in depth'

I'm reading 'C# in depth' by Jon Skeet currently and there's an example depicting Code Contracts with an abstract class implementing an interface which features as an accompanying class for the interface, in Code Contracts' terms: a 'Contract Class…
Aage
  • 5,932
  • 2
  • 32
  • 57
18
votes
1 answer

"Invariant unproven" when using method that creates a specific new object in its return statement

The following simple code will yield an "invariant unproven" warning by the static checker of Code Contracts, although there is no way _foo can be null. The warning is for the return statement inside UncalledMethod. public class Node { public…
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
17
votes
3 answers

Code Contracts and Asynchrony

What is the recommended way for adding postconditions to async methods which return Task? I have read the following suggestion: http://social.msdn.microsoft.com/Forums/hu-HU/async/thread/52fc521c-473e-4bb2-a666-6c97a4dd3a39 The post suggests…
17
votes
2 answers

Pros/cons of different methods for testing preconditions?

Off the top of my head, I can think of 4 ways to check for null arguments: Debug.Assert(context != null); Contract.Assert(context != null); Contract.Requires(context != null); if (context == null) throw new ArgumentNullException("context"); I've…
mpen
  • 272,448
  • 266
  • 850
  • 1,236
1 2
3
43 44