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

Using Code Contracts to define an immutable interface?

Can I use Code Contracts to define read-only, invariant properties on an interface? I.e. properties which always yield the same value after instantiation?
Lawrence Wagerfield
  • 6,471
  • 5
  • 42
  • 84
10
votes
2 answers

Why can't I add Contract.Requires in an overridden method?

I'm using code contract (actually, learning using this). I'm facing something weird to me... I override a method, defined in a 3rd party assembly. I want to add a Contract.Require statement like this: public class MyClass: MyParentClass { …
Steve B
  • 36,818
  • 21
  • 101
  • 174
10
votes
2 answers

How to make Code Contracts believe that variable is not null?

I have some factory method public T Create () where T : class { Contract.Ensures(Contract.Result() != null); T result = this.unityContainer.Resolve(); return result; } The I try to build the project i…
Tom Kris
  • 1,227
  • 1
  • 8
  • 15
10
votes
2 answers

What happened to Code Contracts?

Code contracts was all over the blogosphere years ago before the .NET 4 release, the runtime components included in .NET 4 and the static checker made available in the more expensive Visual Studio 2010 editions. The buzz around code contracts appear…
SoftMemes
  • 5,602
  • 4
  • 32
  • 61
10
votes
2 answers

Code contracts, forall and custom enumerable

I am using C# 4.0 and Code Contracts and I have my own custom GameRoomCollection : IEnumerable. I want to ensure, that no instances of GameRoomCollection will ever contain a null value element. I don't seem to be able to this, though.…
Stephan
  • 101
  • 4
10
votes
3 answers

Code Contracts in C# and null checking

In my code i do this a lot: myfunction (parameter p) { if(p == null) return; } How would I replace this with a code contract? I'm interested in finding out if a null has been passed in and have it caught by static checking. I'm interested in…
Xander
  • 9,069
  • 14
  • 70
  • 129
10
votes
5 answers

Should we allow null/empty parameters?

I recently had a discussion with a co-worker on whether we should allow null or empty collections to be passed as method parameters. My feeling is that this should cause an exception, as it breaks the method's 'contract', even if it does not…
Zecrates
  • 2,952
  • 6
  • 33
  • 50
10
votes
5 answers

Design by contracts and constructors

I am implementing my own ArrayList for school purposes, but to spice up things a bit I'm trying to use C# 4.0 Code Contracts. All was fine until I needed to add Contracts to the constructors. Should I add Contract.Ensures() in the empty parameter…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
10
votes
2 answers

Can I use .NET 4 Code Contracts and remain compatible with .NET 3.5?

.NET 4 introduced Code Contracts as a new feature. I'd like to use CC, but provide files that can still run in 3.5 SP1. Is that possible? Can I only use parts of the new functionality? Apparently it is possible to have CC only do static checks…
mafu
  • 31,798
  • 42
  • 154
  • 247
10
votes
2 answers

Is there a common PureAttribute that ReSharper and Code Contracts can both use?

I'm writing in C# with ReSharper 8.0 and VS2012 for .NET 4.0. ReSharper includes an attribute: JetBrains.Annotations.PureAttribute. This is used to provide the inspection "Return value of Pure method is not used". Code Contracts includes an…
Varon
  • 33
  • 1
  • 10
10
votes
3 answers

ReSharper Possible Null Exception when null is already checked

This is ReSharper 7 with Visual Studio 2012. With the sample below // This code works fine and as expected and ReShrper is happy with it if (!string.IsNullOrWhiteSpace(extension) && extension.Length == 3) { // do something } // ReSharper…
Adam
  • 3,872
  • 6
  • 36
  • 66
10
votes
1 answer

Why .net exception is not caught?

Consider the following "Safe" program: internal class Safe { public static void SafeMethodWillNeverThrow() { try { var something = ThrowsNewException(); Func x = p =>…
Alexander Bartosh
  • 8,287
  • 1
  • 21
  • 22
9
votes
2 answers

Using Code Contracts to specify a return value may be null

Is there a way of explicitly specifying that a return value can be null using Code Contracts? My worry is that methods without a Contract.Ensures(Contract.Result() != null) may be incorrectly 'fixed' in the future to include the…
Lawrence Wagerfield
  • 6,471
  • 5
  • 42
  • 84
9
votes
2 answers

Should I turn on runtime checking of code contracts for .NET 4.0 on release builds?

Assuming all new .NET 4.0 code I see that there is the option to turn them on. However I don't see what the best practice is? Is the best practice that once static checking is done, you really don't need to do runtime checking (since the compiler…
Mark
  • 5,223
  • 11
  • 51
  • 81
9
votes
1 answer

Code Contracts for mono?

Does mono support Code Contracts? I.e. if I build a class library, can mono users use my assembly? If not, are there any alternative libraries? Preferably supporting static analysis (through a plugin or similar in visual studio)
jgauffin
  • 99,844
  • 45
  • 235
  • 372