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

Can I use SuppressMessage on a framework method?

I would like to implement the following suggestion from CodeContracts: CodeContracts: MyModule: Method MyModule.MyClass.MyMethod: To mask *all* warnings issued like the precondition add the attribute: [SuppressMessage("Microsoft.Contracts",…
Dave Neeley
  • 3,526
  • 1
  • 24
  • 42
5
votes
2 answers

C# Code Contracts -- How to ensure that a collection of items contains items with unique properties?

Basically, I have the following: public class MyClass { public MyClass(ICollection coll) { Contract.Requires(coll != null); Contract.Requires(Contract.ForAll(coll, obj => obj != null)); …
myermian
  • 31,823
  • 24
  • 123
  • 215
5
votes
2 answers

Moq and Code Contracts

When using class invariants, Code contracts seems to inject code everywhere. Stuff like this [ContractClassFor(typeof(IX))] interface IXContract { [ClassInvariant] void Invariant() { ...…
jameszhao00
  • 7,213
  • 15
  • 62
  • 112
5
votes
1 answer

.NET Core: Code Contracts approach is closed for now?

Some years ago was many information about Code Contracts. I did not have time to learn it and found this time only now :) But when I try to use it, I see, that Visual Studio 2017 does not support it, CC tool is updated last time more than 3 years…
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
5
votes
1 answer

.NET 4 Code Contracts: "requires unproven: source != null"

I just started using code contracts in my project. However, I have a problem with my repository implementation, which queries my database using the Entity Framework. I have the following method: public IEnumerable
Vern
  • 233
  • 3
  • 13
5
votes
1 answer

Code Contracts: IEnumerator.GetEnumerator() weird inherited contract?

I am using Code Contracts together with the Code Contracts Editor Extensions VS2010 add-in. I have a class that implements the IEnumerable interface, and I've implemented an iterator block for the GetEnumerator() method. Above it, I can see the…
Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
5
votes
2 answers

Conditional Attribute Exception with Code Contracts

I'm getting an exception when I use code contracts on the following code: public void Debug( dynamic message1, dynamic message2 = null, dynamic message3 = null, dynamic message4 = null, …
photo_tom
  • 7,292
  • 14
  • 68
  • 116
5
votes
2 answers

How do you assert in algorithimic code in .NET?

I am currently developing a small AI framework ( genetic algorithms / neural networks) in C#, for a university project. My first concern is developing a reusable framework, so I am designing everything to be pretty modular. I know I am paying off a…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
5
votes
2 answers

Why I still get Code Contracts : Ensure unproven warning?

Below is a very simple example. When I turn on the static analysis warnings, I still get Warning CodeContracts: ensures unproven: Contract.Result() != string.Empty on the line return string.Format("{0}, {1}", movie.Title,…
Simon
  • 53
  • 3
5
votes
1 answer

Code Contracts Rewrite Failed - libpaths order

My Solution/Project builds fine with code contracts turned off for this particular project. When I turn on Perform Runtime Contract Checking on my project, the build fails. The CC rewriter starts to kick up hundreds of messages along the lines of:…
jasper
  • 3,424
  • 1
  • 25
  • 46
5
votes
3 answers

Specify code contract on Func parameters?

Say I have the following public T Example(Func f) { Contract.Requires(f != null); Contract.Requires(f() != null); // no surprise, this is an error ... } Is there any way to specify that my Func parameters must obey some contracts?
Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115
5
votes
2 answers

Create code contracts for a legacy library

The ultimate goal is to specify contracts for a class that resides in an external assembly that I don't have control over (i.e. I cannot just add contracts to that class directly). What I have tried so far: ContractClassFor attribute. Doesn't work,…
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
5
votes
1 answer

Code Contracts: ContractClassFor when dealing with a generic abstract class?

So, I have a little problem here. Suppose I have: public class Repository where TEntity : class { public abstract void Add(TEntity entity); // ...and so on... } And now I want to define a contract class, like so: public class…
user438034
5
votes
1 answer

Are code contracts for vs 2015 stable now?

I'm thinking about adding Code Contracts to our project. We use C# and Visual Studio 2015. I have read that Code Contracts were broken for this version because of new Roslyn Compiler. Is it still true? Also if it turns out that I will be the only…
SENya
  • 1,083
  • 11
  • 26
5
votes
1 answer

CC Suggesting Redundant Ensures

I have a piece of code which looks a little like this: public TReturn SubRegion(TParam foo) { Contract.Requires(foo!= null); Contract.Ensures(Contract.Result() != null); if (!CheckStuff(foo)) foo.Blah(); return…
Martin
  • 12,469
  • 13
  • 64
  • 128