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
1
vote
0 answers

Visual Studio 2013 stops working after installation of Code Contracts

I recently installed Visual Studio 2013 on my dev machine and was missing Code Contracts support afterwards (had it installed previously), so I reinstalled Code Contracts. Immediately thereafter, Visual Studio refused to start up with the error…
Peter Brennan
  • 1,366
  • 12
  • 28
1
vote
1 answer

Why won't this Code Contracts relationship prove?

I have a method that starts like this: public static UnboundTag ResolveTag(Type bindingType, string name, string address) { Contract.Requires(bindingType != null); var tags =…
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
1
vote
0 answers

Portable library doesn't build with Code contracts

I'm trying to build a wp8.1+win8.1 portable class library with enabled Runtime checking Code contracts, but it fails with the following error: Reading assembly 'Newtonsoft.Json' from…
Viachslau
  • 361
  • 2
  • 11
1
vote
1 answer

No warning on nulls passed to method with Contract.Requires

My goal is static contract checking to catch / avoid passing around nulls, and I'm new to contracts. I'm using Contract.Requires(param!=null) in a method (Link ctor) and as a test, I call it with null parameters, and I expect it to warn me, but it…
toddmo
  • 20,682
  • 14
  • 97
  • 107
1
vote
1 answer

How to get Compile-Time Contract Warnings / Errors

I am new to contracts and I took from the overview that it could help you at compile time to discover contract violations. I am not getting a compile time warning or error when I have code that explicitly violates a contract. I would expect the…
toddmo
  • 20,682
  • 14
  • 97
  • 107
1
vote
1 answer

CodeContracts: ccrewrite fails with Object reference not set to an instance of an object

The below code makes ccrewrite blow up! Ideas? BTW, If you comment out the ActualClass, ccrewrite succeeds... [ContractClass(typeof(TestContracts))] interface ITestInterface { bool IsStarted { get; set; } void Begin(); …
Vyas Bharghava
  • 6,372
  • 9
  • 39
  • 59
1
vote
1 answer

Class invariant for mutually exclusive conditions

My class has two private fields and three constructors. One constructor is a default constructor that does not assign any values. The remaining constructors each instantiate one of two fields, ensuring that one field is always null and the other…
Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
1
vote
2 answers

Awkward looking uses of Contract.ValueAtReturn()

I am designing a method that will add an element to an internal list. The structure of the class is something along the lines of: class MyCustomerDatabase { private IList _customers = new List(); public int…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
1
vote
1 answer

Code Contract: malformed when incapsulate require method and unable to use String.Format

It seems that CodeContract from DevLab is a nice tool, but I had two errors in with code: public class SomeClass { private DataTable _dataTable // I don't want to write the same condition more then ones, so incapsulate it private void…
mnsasha
  • 27
  • 4
1
vote
1 answer

Does [Pure] have any implications other than "no visible side-effects" to Code Contracts?

The PureAttribute documentation says: Indicates that a type or method is pure, that is, it does not make any visible state changes Is this the only requirement of a Pure function under in Microsoft Code Contracts? And; does this model assume that…
user2864740
  • 60,010
  • 15
  • 145
  • 220
1
vote
1 answer

Code contract invariant violation in C# using Entity Framework

I'm beginner at EF and code contract, for doing a project I use the EF6 and code contract. As you know in DB first approach, EF automatically generates classes corresponding to the DB entities, I added contracts to the partial classes which I…
1
vote
2 answers

Code Contracts Error on Build Agent?

I have just started using code contracts to make my preconditions neater and more readable, hoping to get some further benefits like static checking later. However as I committed my code and a build was done it failed on the unit tests (that test my…
sprocket12
  • 5,368
  • 18
  • 64
  • 133
1
vote
2 answers

Throw specific exception for a violation of a contract on an automatic property

I can specify a contract for an automatic property like this (example taken from the CC documentation): public int MyProperty { get; set ; } [ContractInvariantMethod] private void ObjectInvariant () { Contract. Invariant ( this .MyProperty >= 0…
ZbynekZ
  • 1,532
  • 10
  • 16
1
vote
0 answers

Code Contract False Positive and Suppression

I'm starting to use code contracts and trying to clear a false positive warning where code contracts is not recognizing the fact that the dependency property can be set to null and therefore is flagging that the conditional checks are unnecessary.…
Mark Smith
  • 1,085
  • 8
  • 19
1
vote
1 answer

Understanding code contracts for interfaces

I want to create a code contract for a certain interface, however I'm having a hard time believing that it is actually done this way. [ContractClass(typeof(AsyncCacheProviderContract))] public interface IAsyncCacheProvider { Task
xvdiff
  • 2,179
  • 2
  • 24
  • 47