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.

650 questions
59
votes
6 answers

Really trying to like CodeContracts in C#

I am finally playing catchup with everything new that has been added in to the .NET 3.5/4.0 Frameworks. The last few days I have been working with CodeContracts and I am really trying hard to like them. I am curious what other people think of the…
Chris Baxter
  • 15,423
  • 9
  • 49
  • 70
52
votes
7 answers

ReSharper - Possible Null Assignment when using Microsoft.Contracts

Is there any way to indicate to ReSharper that a null reference won't occur because of Design-by-Contract Requires checking? For example, the following code will raise the warning (Possible 'null' assignment to entity marked with 'NotNull'…
51
votes
5 answers

Does Visual Studio 2017 work with Code Contracts?

I just installed the newly released Visual Studio 2017 Enterprise (RC). I'm having trouble getting it to work with Code Contracts, however. I have no problem using Code Contracts with Visual Studio 2015. Am I missing something?
user2106007
  • 677
  • 1
  • 7
  • 10
47
votes
4 answers

How come you cannot catch Code Contract exceptions?

System.Diagnostics.Contracts.ContractException is not accessible in my test project. Note this code is purely myself messing around with my shiney new copy of Visual Studio, but I'd like to know what I'm doing wrong. I'm using the professional…
Finglas
  • 15,050
  • 9
  • 51
  • 85
45
votes
2 answers

Debug.Assert vs Code Contract usage

When should I debug.assert over code contracts or vice versa? I want to check precondition for a method and I am confused to choose one over the other. I have unit tests where I want to test failure scenarios and expect exceptions. Is it a good…
Carbine
  • 7,448
  • 3
  • 26
  • 52
43
votes
4 answers

How mature is the Microsoft Code Contracts framework?

Microsoft has recently put a release of their Code Contracts framework on DevLabs with a commercial license. We're interested on using them in our project (mostly C#, some C++/CLI) to gradually replace all the custom validation code, but I'm keen to…
Greg Beech
  • 122,952
  • 42
  • 199
  • 241
38
votes
6 answers

.NET exception caught is unexpectedly null

See below for an explanation of what is going on I have a really weird issue where the exception caught is null. The code uses MEF and tries hard to report composition errors. Using the debugger I can see the exception being thrown (an…
Martin Liversage
  • 96,855
  • 20
  • 193
  • 238
37
votes
1 answer

False positive: precondition is redundant

Why do I get the following warning for this trivial code sample as soon as the Warning Level is on the 2nd level or higher? public int Foo(int a) { if (a >= 0) throw new ArgumentException("a should be negative", "a"); …
Voo
  • 26,852
  • 9
  • 70
  • 145
37
votes
4 answers

.NET 4.0 code contracts - How will they affect unit testing?

For example this article introduces them. What is the benefit? Static analysis seems cool but at the same time it would prevent the ability to pass null as a parameter in unit test. (if you followed the example in the article that is) While on the…
Finglas
  • 15,050
  • 9
  • 51
  • 85
36
votes
4 answers

What is a practical usage of Code Contracts in .NET 4.0?

In order to fully understand and take advantage of the new features and enhancements provided with the coming of the new .NET Framework 4.0, I would like to get an example of real-world application of Code Contracts. Anyone has a good example of…
Will Marcouiller
  • 22,531
  • 19
  • 89
  • 142
35
votes
3 answers

Code contracts - Assume vs Requires

What's the diference between these two statements ? Contract.Requires(string.IsNullOrWhiteSpace(userName)); Contract.Assume(string.IsNullOrWhiteSpace(userName));
user137348
  • 9,610
  • 17
  • 62
  • 88
35
votes
1 answer

Microsoft Code Contracts and CI build server

We are migrating to .NET 4 and very interested in implementing new Design By Contract capabilities. As we know Code Contract engine requires installation of Code Contract addin and VS Ultimate or Premium (for static checking). Here is my…
Sergey Mirvoda
  • 3,119
  • 2
  • 23
  • 29
34
votes
2 answers

Should the Code Contracts static checker be able to check arithmetic bound?

(Also posted on the MSDN forum - but that doesn't get much traffic, as far as I can see.) I've been trying to provide an example of Assert and Assume. Here's the code I've got: public static int RollDice(Random rng) { …
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
33
votes
1 answer

How to properly use Code Contracts in .NET Core

I wonder, how to properly use Code Contracts in .NET Core, so far I tried to add CC to my project, compile and debug. I'm confused by message, which is appearing in each call which uses Contract.Requires, and information found by googling. The…
Jiří Zajíček
  • 340
  • 1
  • 3
  • 9
33
votes
2 answers

Code Contracts: How do I supply a contract class for a generic interface?

I'd like to specify a contract for this generic interface, using Code Contracts: interface IRandomWriteAccessible { T this[uint index] { set; } uint Length { get; } } The documentation says to use the ContractClass attribute when…
stakx - no longer contributing
  • 77,057
  • 17
  • 151
  • 248
1
2 3
43 44