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

Calculate Code Metrics ignoring Code Contracts

Is there anyway to calculate the Code Metrics for a VS 2010 Ultimate solution, but to omit the Code Contracts? Right now, my best idea is to do a calculation, dump the excel file, then reflect over the IL of each class, count the amount of lines…
smartcaveman
  • 41,281
  • 29
  • 127
  • 212
1
vote
2 answers

Enable static contract checker to prove a Property non-null based on some other property

Assume the following code: public class CC3 { private string _field; private bool _someFlag; public string Property { get { return _field; } } public bool SomeFlag { get { return _someFlag; } } …
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1
vote
1 answer

Why does TFS2012 report build as successful if Code Contracts rewriter did not run?

I build my solution but CC tools are not installed on build server. So no rewrite was done. Now I'm curios why msbuild reports build as successfull if not all tasks were finished? P.S. I'm completely unexperienced in msbuild so if my question sounds…
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
1
vote
2 answers

Issue with Code Contract in c#

I am facing a problem that I can not figure out. Say I have two methods: public void Method1(object obj) in ViewModel class and public void Method2(object obj) in Model class. Method2 gets called from Method1 using the instance of Model class(say,…
Anirban Paul
  • 1,065
  • 1
  • 16
  • 22
1
vote
2 answers

How to Log error while using Code Contracts

I need to log exception (even in release version) in my application. I am using a static method Log(Exception ex) of a class CLog to log the exception. I am also using Code Contracts and using both static and runtime checking. Please consider the…
Anirban Paul
  • 1,065
  • 1
  • 16
  • 22
1
vote
1 answer

How to hint static checker to understand simple arithmetics?

I am working on an object that encapsulates a bitmap as an array of pixels. The array is one dimensional, and I store the width of the image in a readonly field. I also added a property that calculates the height based the pixel array length and the…
WebMonster
  • 2,981
  • 2
  • 22
  • 29
1
vote
2 answers

Code contracts: static checking fails on IEnumerable.Min

I get some warnings on the following code containing code contracts. public static int Min(IEnumerable set) { Contract.Requires(set != null); Contract.Requires(set.Any()); Contract.Ensures(Contract.ForAll(set, x => x >=…
mbue
  • 1,591
  • 2
  • 14
  • 34
1
vote
1 answer

Why is Code Contract analysis not installed by default

We're just beginning a new project and we're keen to include testing from the ground up. While we were looking at which unit test solution to use I came across Code Contracts which seem like they offer an easier way to check things like null…
MrEdmundo
  • 5,105
  • 13
  • 46
  • 58
1
vote
0 answers

What are masked assertions in Microsoft Code Contracts?

Possible Duplicate: How to find 'masked' assertions in MS Code Contracts I started with Code Contracts under C# 4.0 recently and I get messages like the following: CodeContracts: Checked 50 assertions: 33 correct (17 masked) I've been looking…
1
vote
2 answers

Visual Studio 2012 and Code contracts for interfaces

I have a visual studio solution with projects containing interfaces and contracts decorated respectively with ContractClass and ContractClassFor. The solution builds correctly under Visual Studio 2010, but it doesn't build with Visual Studio 2012.…
fra
  • 3,488
  • 5
  • 38
  • 61
1
vote
3 answers

Using System.Reflection in code contracts static analysis

Can I use System.Reflection classes and methods in Code Contracts construction, that would check during static analysis? I want to define contract like that: [ContractInvariantMethod] private void ObjectInvariant() { …
mao
  • 1,364
  • 3
  • 14
  • 26
1
vote
2 answers

Is there any best practice/guidelines available for using Code Contracts, Pex and 'Fake' framework?

Is there any best practice/guidelines available for using Code Contracts, Pex and Fake framework? Not able to find something concrete available with all 3 combined.
1
vote
2 answers

CodeContracts: How to fulfill Require in Ctor using this() call?

I'm playing around with Microsoft's CodeContracts and encountered a problem I was unable to solve. I've got a class with two constructors: public Foo (public float f) { Contracts.Require(f > 0); } public Foo (int i) : this ((float)i) {} The…
mafu
  • 31,798
  • 42
  • 154
  • 247
1
vote
1 answer

Code contracts and interface implementations - What are some reasons for the 1-1 relationship

Learning more about code contracts, they seem like something I want to use in my project. Given the way that I'm structuring my web-service-layer (an abstraction of our service layer accessed from our MVC controllers) I find myself wondering why…
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
1
vote
1 answer

CodeContracts: Reuse of assumptions/asserts?

I've posted this on the CodeContracts forum at the MSDN but apparently no one knows or bothers to look into this issue. I've tried to reduce the repetitive asserts and make it more reusable but unfortunately this doesn't work can you explain…
iam3yal
  • 2,188
  • 4
  • 35
  • 44