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

Code contracts: Array access upper bound warning when mapping to 2d array

Good day. I'm testing out C# code contracts. I've been working on some matrix implementations, and wanted to use code contracts to do arithmetic checking (eg. when is a matrix multiplication valid). In order to store the data, I use a one…
Chillersanim
  • 455
  • 3
  • 13
1
vote
1 answer

Code Contracts: Invariants not respected in static method

I read about similar questions: Code Contracts: Ensure unproven on string method Code Contracts: Why are some invariants not considered outside the class? but it still baffles me that this minimal example cannot be statically proved: public class…
Yin Zhong
  • 35
  • 4
1
vote
1 answer

How to tell the static checker that a property never changes when it is unprovable?

My class has a property that is initialized in the constructor and is never supposed to change. Methods all around my codebase accept that class as a parameter and rely on that property satisfying a certain condition. The key point is that it is…
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
1
vote
2 answers

Why doesn't code contract display message?

I have the following as the first line in a method: Contract.Requires(param1 != null, "param1 can't be null"); When param1 comes in null, nothing happens and code below the contract continues to execute. Is something else needed for the message to…
4thSpace
  • 43,672
  • 97
  • 296
  • 475
1
vote
2 answers

Visual Studio 2015 Code Contracts Won't Update Properly

I have a very annoying problem. I have installed Visual Studio 2015 Enterprise with Update 3. One important thing to notice, I guess, is that it is not installed on C:\Program Files..., but on D:\Program Files... I have installed the latest Code…
1
vote
0 answers

Suppressing Code Contract warnings for DbContext.ChangeTracker

I'm trying to get rid of Code Contract warnings for Entity Framework classes and methods by using [assembly: SuppressMessage("Microsoft.Contracts", "Requires", Target = "System.Data.Entity")] [assembly: SuppressMessage("Microsoft.Contracts",…
Tim Pohlmann
  • 4,140
  • 3
  • 32
  • 61
1
vote
1 answer

Code contracts problem

Consider the following code : public class RandomClass { private readonly string randomString; public RandomClass(string randomParameter) { Contract.Requires(randomParameter != null); …
Diadistis
  • 12,086
  • 1
  • 33
  • 55
1
vote
2 answers

Has someone experiences with metrics for Design-By-Contract or can recommend metrics to measure the usage of Design-By-Contract in a code base?

We are currently introducing Design-by-Contract to a software development group of about 60 developers, which are developing different components. We started by defining Design-By-Contract policies for C# and Java. To measure the progress we are…
SvenG
  • 229
  • 3
  • 5
1
vote
1 answer

.NET Code Contracts - ProjectA.exe cannot find ProjectB.Contracts.dll when both are in same solution

I have a C# solution in VS2013, with the Code Contracts extension installed. In my solution I have an application project (ProjectA) and a class library project (ProjectB). ProjectA references ProjectB, and most of ProjectB's public members have…
JamesFaix
  • 8,050
  • 9
  • 37
  • 73
1
vote
1 answer

How can I ensure that an iterator method will not yield any null items?

I'm wondering whether it is possible to ensure (using code-contracts) that an iterator method will never yield a null item. This simplified method: public static IEnumerable CreateSomeObjects() { …
Mårten Wikström
  • 11,074
  • 5
  • 47
  • 87
1
vote
1 answer

Code contracts warning DateTime.HasValue always evaluates to a constant value

I have a problem which may be a bug in code contracts or I'm just missing something. I have a class with a nullable DateTime property DateValue which gets set by the constructor. The class's == overload states that 2 objects are equal if…
Keith
  • 20,636
  • 11
  • 84
  • 125
1
vote
1 answer

Contract class references member which is not part of the abstract class/interface being annotated

Hi I'm Trying to make a simple code contract for a setter which states a DateTime Has to be at least fifteen years old. If I do the validation in a member of the contract class the compiler yields Contract class…
borja gómez
  • 1,001
  • 8
  • 19
1
vote
2 answers

Can you put Code Contracts on Private Fields?

For the sake of simplicity, say I have a private field that caches my collection's count: private int _count; I would like to ensure that the count is never below zero. I can check this in the invariant: [ContractInvariantMethod] private void…
Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44
1
vote
2 answers

Is CodeContract similar to FxCop?

Please clarify, is the Code Contracts is similar to FxCop and StyleCop? As per the online references, we need to add Codes for implementing the code contract conditions inside the function of existing code. public void Initialize(string name, int…
user2960882
  • 57
  • 1
  • 8
1
vote
2 answers

C# Usage of Redundant Code Contract-Preconditions

I did not find the info by reading the usage guidelines, so I ask my question here: Assuming the following situation: /// /// Initalisiert eine neue Instanz des SettingsManager /// ///
user3698624
  • 225
  • 1
  • 10