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

Using invariant for IDisposable

Consider the following IDisposable class: class MyClass : IDisposable { public bool IsDisposed { get; private set; } = false; public void Dispose() { IsDisposed = true; } } Every method in this class, including Dispose(),…
Libor
  • 3,285
  • 1
  • 33
  • 41
6
votes
1 answer

Code Contracts: How to deal with inherited interfaces?

I'm using MS Code Contracts and have run into a snag with using interface inheritance and ContractClassFor attributes. Given these interfaces and contract classes: [ContractClass(typeof(IOneContract))] interface IOne {…
scobi
  • 14,252
  • 13
  • 80
  • 114
6
votes
4 answers

How to avoid "source !=null" when using Code Contracts and Linq To Sql?

I have the following code using a normal data context which works great: var dc = new myDataContext(); Contract.Assume(dc.Cars!= null); var cars = (from c in dc.Cars where c.Owner == 'Jim' select c).ToList(); However when I…
RandomProgrammer
  • 1,570
  • 1
  • 14
  • 23
6
votes
3 answers

What does "Contract can't be in try block" mean?

I'm using the 3.5 library for microsoft code contracts public object RetrieveById(int Id) { //stuff happens... Contract.Ensures(newObject != null, "object must not be null"); return newProject; //No error message if I move the…
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
6
votes
1 answer

Code Contracts and Tasks

Code contracts simply treats Tasks as it would with any other variable, instead of waiting for the result asynchronously. So, the following scenario will not work, and cause a Contracts exception since at the time the method returns, its an…
user3513472
6
votes
3 answers

Code Contracts and Inheritance(Precondition on overridden method)

Currently code contracts do not allow preconditions on members in derived classes where the member already has a precondition set in the base class(I actually currently get a warning and not an error). I do not understand the logic behind this. I…
6
votes
2 answers

Handling the usual errors: If-Then-Throw blocks vs. Code Contracts vs. an Assert class

When I start writing a method, I usually check for exceptional conditions first in the method, using If-Then-Throw blocks. public void ReadFile(string filePath) { if (string.IsNullOrEmpty(filePath) { throw new…
Chris Akridge
  • 385
  • 3
  • 14
6
votes
3 answers

Getting Code Contracts to work in Visual Studio 2010

I have the following code: class Program { static void Main(string[] args) { Console.WriteLine(SqrtRoot(0)); Console.WriteLine(SqrtRoot(10)); Console.WriteLine(SqrtRoot(-10)); Console.ReadKey(); } …
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
6
votes
1 answer

Code Contracts for C# does not work when ContractFor is on a different assembly

I am trying to define code contracts for an interface using ContractClass and ContractClassFor. It works fine when everything is in the same assembly, but if I put the interface definition and its respective contract class in a different assembly…
6
votes
2 answers

Is this a bug in the static contract checker?

If I write this: public sealed class Foo { private int count; private object owner; private void Bar() { Contract.Requires(count > 0); Contract.Ensures(owner == null || count > 0); if (count == 1) …
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
6
votes
1 answer

How can I use Code Contracts in a C++/CLI project?

I recently stumbled upon Code Contracts and have started using them in my C# projects. However, I also have a number of projects written in C++/CLI. For C# and VB, Code Contracts offer a handy configuration panel in the project properties dialog.…
Daniel Wolf
  • 12,855
  • 13
  • 54
  • 80
6
votes
2 answers

Code Contracts in Mono

The following code: Contract.Requires(command != null, Resources.Messages.CommandNotSpecified); calls Contract.AssertMustUseRewriter (ContractFailureKind kind, System.String message) which seems to be caused by not configuring…
6
votes
2 answers

CodeContracts: false warning "Possibly unboxing a null reference"

In the image above, you can see a warning from Code Contracts. I don't think this is legit, as this can never be null. Is this a bug or am I missing something? This property is a member of the following class: public class…
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
6
votes
1 answer

Why is Marshal.DestroyStructure considered Pure?

Marshal.DestroyStructure is marked with the Pure attribute in the .NET Framework but I'm unsure as to why when it clearly has an effect on the context calling it. The state is modified (the pointer is freed) even if it doesn't directly modify the…
Rushyo
  • 7,495
  • 4
  • 35
  • 42
6
votes
0 answers

CodeContracts and resharper vs2012 not working

I have Resharper and it's a fantastic tool Starting a projects and I need to use CodeContracts. However Resharper ignores them. After checking a few blogs I came across this…
user9969
  • 15,632
  • 39
  • 107
  • 175