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

Contract.Ensures and Exception Handling

I recently discovered the .NET Contracts API, and, although I don't like the way of implementation using methods and not an extended syntax (Sing# did it right, in my opinion), I prefer using them over the old / regular way using if's for e.g.…
Moritz Gunz
  • 702
  • 6
  • 15
1
vote
1 answer

Validating parameters properties with Code Contracts

I had a discussion with a colleague regarding the usage of Code Contracts to perform prerequisites checks. Let's say we have the following code: namespace Project { using System; using System.Diagnostics.Contracts; public class Thing …
Albireo
  • 10,977
  • 13
  • 62
  • 96
1
vote
1 answer

Code Contract on property in Interface

Hi iam trying to put my code contract on interface on my class and i write something like this: [ContractClass(typeof(MyClassContract))] interface IMyClass { int Id { get; set; } } [ContractClassFor(typeof(IMyClass))] sealed class…
gt.guybrush
  • 1,320
  • 3
  • 19
  • 48
1
vote
1 answer

How to enable code contracts in Visual studio 2008?

I am (mainly) a .NET developer and for my project I use visual studio 2008. After watching this video: http://channel9.msdn.com/Blogs/Peli/Getting-started-with-Code-Contracts-in-Visual-Studio-2008 it became clear for me that I want to use code…
Daan
  • 2,478
  • 3
  • 36
  • 76
1
vote
1 answer

CodeContracts on interfaces doesn't works across different projects in one solution

I have a solution where one projects contains public interfaces & another - their implementations. Interfaces is decorated with contracts. It turned out during testing that if interface implementation is in the same project as the corresponding…
JSP
  • 457
  • 1
  • 7
  • 19
1
vote
1 answer

Unit Testing interface contracts in C#

Using the Code Contracts tools available in VS2010 Beta 2, I have defined an interface, a contract class for that interface and two classes that implement the interface. Now when I come to test the code, I want to test the implementation classes so…
Colin Desmond
  • 4,824
  • 4
  • 46
  • 67
1
vote
1 answer

why is CodeContracts static checker suggesting that I Contract.Assume(a) right after I Contract.Ensure(a)?

Basically, I have a virtual method to propagate certain mandatory postconditions to subclasses. Here's a simplified version and the strange warnings the static checker generates (edit - my example was incomplete. It's right now): public abstract…
1
vote
1 answer

CodeContracts: Invoking this method will always lead to an error

Still learning code contracts. When I create a small test, I get the following message from the checker: CodeContracts: Invoking this method will always lead to an error. If this is wanted, consider adding Contract.Requires(false) to document…
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
1
vote
2 answers

Why is CodeContracts recommending a null check in a foreach loop

I have this code: foreach (UIElement uiElement in list) { uiElement.SetValue(Grid.ColumnProperty, colunmn++); uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count - 1); _uiRoot.Children.Add(uiElement); } It runs fine, but…
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
1
vote
2 answers

Code Contracts, Tests, Assertions, and Exceptions in .NET, when to use which?

First off, I want to acknowledge that I understand that these are separate concepts with their own domain of purpose. With that being said I occasionally find myself wondering if the best way to handle something is with Contracts, good testing, or…
Daniel Green
  • 634
  • 5
  • 14
1
vote
1 answer

Should Contract.Ensures be used in finalizers and Dispose methods?

I read here that invariants are not checked for object finalizers or for any methods that implement the Dispose method, but it doesn't state the reason. I suspect the reason is that invariant conditions may no longer hold true when the object is…
Ɖiamond ǤeezeƦ
  • 3,223
  • 3
  • 28
  • 40
1
vote
2 answers

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?
x2.
  • 9,554
  • 6
  • 41
  • 62
1
vote
1 answer

Is there a benefit in writing code contract instead of straight up check logic code?

We are building business application not API for others to use, in this case, I prefer to use our validation logic in the if/then/throw model. I was told, it is better to use Code Contracts. I do not see any benefits, is there any obvious benefits…
Nair
  • 7,438
  • 10
  • 41
  • 69
1
vote
2 answers

Code contracts on value types

I've just started playing with code contracts, and while promising, they seem to have some limitations with respect to value types. For instance: public struct Wrap where T : class { readonly T value; public Wrap(T value) { …
naasking
  • 2,514
  • 1
  • 27
  • 32
1
vote
1 answer

Contract.Requires in exception ctor fails with error CC1027: Malformed contract

I am trying to write an exception and on the ctor I added a Contract.Requires declaration. for some reason the compilation of this fails with error CC1027: Malformed contract I am using the latest version (1.4.60317.12) of code contract addin to…
Dani Avni
  • 423
  • 5
  • 14