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
4
votes
5 answers

Code Contracts what to do with exceptions

My main question is what to do with those Exceptions that I throw ? For example: Contract.Requires(foo != null); What to do in uper levels of the function call with this thrown exception ? Should I ignore it , and just when I see it know that…
Night Walker
  • 20,638
  • 52
  • 151
  • 228
4
votes
2 answers

Out-of-the-box Code Contracts in .NET 4.0

I'd really like to try out the new Code Contract in Visual Studio 2010, but I don't want to install additional extensions to Visual Studio (since my code in shared with my coworkers). Now, when targeting .NET 4.0 I can use the new…
Jens
  • 25,229
  • 9
  • 75
  • 117
4
votes
4 answers

How can I use code contracts to check the value of a Lazy without losing the advantages of lazy evaluation?

I have code that looks something like this: public class Foo { private readonly Lazy lazyBar; public Foo() { lazyBar = new Lazy(() => someExpression); } public string Bar { get { return…
Matthew
  • 28,056
  • 26
  • 104
  • 170
4
votes
2 answers

What tooling do you use to do Design by Contract?

I used to use Microsoft CodeContracts for three weeks and now half of my code is just contracts. I have dozens of unproved places, I cannot use runtime-check because IL rewrite prevents coverage tool to show something and compile time is less then…
Mike Chaliy
  • 25,801
  • 18
  • 67
  • 105
4
votes
2 answers

What keywords/tools are there to help the compiler optimise

Often we're told things like, If you're calling a method with a return value that doesn't change, take it out of the loop. for example when writing code like: for(int i=0; i < Instance.ExpensiveNonChangingMethod(); i++) { // Stuff } I was…
George Duckett
  • 31,770
  • 9
  • 95
  • 162
4
votes
2 answers

Is the Random.Next code contract incorrect?

I've installed a plugin (Code Contract Editor Extensions by Microsoft) which displays all code contracts for .NET. When I look at the contract for Random.Next it says ensures result <= maxValue while MSDN states that maxValue is exclusive.…
jgauffin
  • 99,844
  • 45
  • 235
  • 372
4
votes
1 answer

Are code contracts supported in .net core?

In the .net framework there were Code Contracts which allowed me to specify pre/post conditons in my code. Are they supported in .net core/.net 5?
4
votes
2 answers

Code Contracts in C# 4.0

I made a method like this class PersonCollection { [Contracts.CanReturnNull] //dont know if something like this exists? IPerson GetPerson(Guid personId) { if (this.persons.Contains(personId)) return this.persons[personId]; …
schoetbi
  • 12,009
  • 10
  • 54
  • 72
4
votes
2 answers

How to Add implementation to Interface code contract when inheriting off interface

My example is a situation where the interfaces that inherit of the base interface need to add post conditions that are a result of their additional fields - the example occured when i decided to have an IInitialise interface as interfaces that…
John Nicholas
  • 4,778
  • 4
  • 31
  • 50
4
votes
1 answer

Force Code Contracts to use sn.exe 4.0

The Code Contracts rewriter uses the Strong Name (sn.exe) utility to resign the rewritten assembly. However in the Output pane of the VS 2010 I see: Microsoft (R) .NET Framework Strong Name Utility Version 3.5.30729.1 Is there a way to force…
Michael Damatov
  • 15,253
  • 10
  • 46
  • 71
4
votes
3 answers

Code Contracts, null checks and value/reference types

Updated post: In order to avoid confusion about what I am and am not doing, I have edited this post radically to include a complete example of the code that causes this problem. In order to make this post readable anyway, all the code is posted at…
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
4
votes
2 answers

How to tell code contracts a delegate specified as argument is Pure?

Consider the following code: int SomeField; void Foo([Pure] Func getData) { Contract.Requires(getData != null); Contract.Requires(getData(this.SomeField) != null); } I get the following warning: Detected call to method…
JBSnorro
  • 6,048
  • 3
  • 41
  • 62
4
votes
1 answer

.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

I'm attempting to use Contracts in my .Net 3.5 (C#) project. I found where I had written something like if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) throw new ArgumentException("Required", "s"); at the beginning of methods. I…
Jason Kleban
  • 20,024
  • 18
  • 75
  • 125
4
votes
4 answers

CodeContract think assigned readonly field can be null

I've got this code: public class CodeContractSample { private readonly List _items = new List(); public IEnumerable Query() { Contract.Ensures(Contract.Result>() != null); //if…
Allrameest
  • 4,364
  • 2
  • 34
  • 50
4
votes
1 answer

code contracts build performance

My question is very straight forward: does any one experience increased build time when code contracts are enabled?
user407665