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

Code Contracts can't invert conditionals?

I have this struct (simplified for brevity): public struct Period { public Period(DateTime? start, DateTime? end) : this() { if (end.HasValue && start.HasValue && end.Value < start.Value) { throw new…
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
13
votes
1 answer

How to generate good code coverage of floating-point logic?

I am hand-crafting new code. I'd like to make sure I leave no stone unturned. Is there anything specific I can do beyond specifying Code Contracts to guide Pex so it produces good coverage in numerically-intensive code? Try searching…
GregC
  • 7,737
  • 2
  • 53
  • 67
12
votes
5 answers

How to unit test with Code Contracts

What is the best practice recommendation for doing TDD with .NET 4.0 Code Contracts? I suppose specifically, my question is that given that one point of TDD is to allow the code to be self documenting and the contract now provides a part of the…
satnhak
  • 9,407
  • 5
  • 63
  • 81
12
votes
4 answers

Checking preconditions in .NET

I'm a fan of the "fail early" strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava: checkArgument(count > 0, "must be positive: %s", count); Is there something similar for .NET?
deamon
  • 89,107
  • 111
  • 320
  • 448
12
votes
2 answers

Code Contracts: Why are some invariants not considered outside the class?

Consider this immutable type: public class Settings { public string Path { get; private set; } [ContractInvariantMethod] private void ObjectInvariants() { Contract.Invariant(Path != null); } public Settings(string…
Romain Verdier
  • 12,833
  • 7
  • 57
  • 77
12
votes
1 answer

Using Contract.ForAll in Code Contracts

Okay, I have yet another Code Contracts question. I have a contract on an interface method that looks like this (other methods omitted for clarity): [ContractClassFor(typeof(IUnboundTagGroup))] public abstract class ContractForIUnboundTagGroup :…
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
12
votes
2 answers

Code Contracts - ForAll - What is supported by static verification

There are numerous information that static checking of Contract.ForAll has only limited or no support. I did lot of experimenting and found it can work with: Contract.ForAll(items, i => i != null) Contract.ForAll(items, p) where p is of type…
Michal Minich
  • 2,387
  • 1
  • 22
  • 30
12
votes
1 answer

Why does static analysis ignore double <= and >= requirement?

I have a very simple class utilizing .NET Code Contracts: public class ContractSquareRoot { /// /// Makes your life much easier by calling Math.Sqrt for you. Ain't that peachy. /// /// The…
vlow
  • 171
  • 6
12
votes
4 answers

Code Contract or if statement?

I just tried to use Code Contracts, and I see no real advantages over an if statement. Consider the following. private static void BindClassesToInterfacesByConvention(string classesEndingWith , string interfacesEndingwith) { …
Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162
12
votes
1 answer

IEnumerable multiple enumeration caused by contract precondition

I have an IEnumerable parameter that is required to be non-empty. If there's a precondition like the one below then the collection will be enumerated during it. But it will be enumerated again the next time I reference it, thereby causing a…
Keith
  • 20,636
  • 11
  • 84
  • 125
11
votes
3 answers

Is Code Contracts failing to spot obvious relationship between Nullable.HasValue and null?

I am experimenting with applying Code Contracts to my code and I've hit a perplexing problem. This code is failing to meet the contract but unless I'm being really thick I would expect it to be able to easily analyse that id must have a value at the…
Wheelie
  • 3,866
  • 2
  • 33
  • 39
11
votes
5 answers

Code Contract : ccrewrite exited with code -1?

I'm new to code contracts. I downloaded the latest build of code contract project (1.4.40314.1) and started to implement it in my project. When i enabled 'Runtume Checking' through Code Contracts Tab in VS2010, i got this Error Error 1 The command…
Code0987
  • 2,598
  • 3
  • 33
  • 51
11
votes
1 answer

CodeContracts: Boolean condition evaluates to a constant value, why?

I'm getting this warning but can't figure out the problem... CodeContracts: warning: The Boolean condition d1.Count != d2.Count always evaluates to a constant value. If it (or its negation) appear in the source code, you may have some dead code…
antak
  • 19,481
  • 9
  • 72
  • 80
11
votes
3 answers

Code Contracts support in Visual Studio Express 2013

I've been developing a C# project in Visual Studio Express 2013 and came across Code Contracts for .NET languages. Impressed by their brevity and the static analysis tool that came with them, I started using them in my code base. However, when I…
Matt Kline
  • 10,149
  • 7
  • 50
  • 87
11
votes
2 answers

How to find 'masked' assertions in MS Code Contracts

I have the following Message-level entry in my Error List from CodeContracts: CodeContracts: Checked 410 assertions: 404 correct (6 masked) I can't figure out: What masked assertions are How to locate the 6 that it mentions Whether or not I should…
Adam Brown
  • 332
  • 3
  • 10