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

Code contracts build reference assembly actions

I am using code contracts and trying to understand which of the build options shall I use and when. The contract assembly build options are defined in project properties Code Contracts -> Contract Reference Assembly: None Build DoNotBuild Any…
oleksii
  • 33,544
  • 11
  • 83
  • 149
32
votes
1 answer

C#: Code Contracts vs. normal parameter validation

consider the following two pieces of code: public static Time Parse(string value) { string regXExpres = "^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$"; Contract.Requires(value != null); …
steveee
  • 321
  • 3
  • 8
28
votes
5 answers

How to deal with Code Contracts warning CC1036 when using string.IsNullOrWhiteSpace?

I have the following code contract: public void F(string x) { Contract.Requires(!string.IsNullOrWhiteSpace(x)); throw new NotImplementedException(); } When compiling, I get the following warning: warning CC1036: Detected call to method…
BartoszKP
  • 32,105
  • 13
  • 92
  • 123
28
votes
1 answer

Usefulness of System.Diagnostics.Contracts in question

I've been playing with the new System.Diagnostics.Contracts class because it seemed very useful at first. Static methods to check inbound arguments, return values, etc. It was a clean interface and could replace lots of if-then statements and…
Ken Foster
  • 368
  • 4
  • 9
27
votes
3 answers

How can I make Code Contracts ignore a specific assembly reference?

I'm making an extension to Visual Studio. Within the code I'm using Code Contracts to make assertions and checks. I set the warning option level to high. What I would like to do is maintain that warning level while ignoring any checks made on EnvDTE…
Crono
  • 9,070
  • 3
  • 35
  • 71
27
votes
1 answer

Why is ccrewrite.exe not doing anything from the command line?

I've got Code Contracts working fine from inside Visual Studio 2010, but I can't get ccrewrite.exe to do anything useful from the command line. Here's a sample app: using System.Diagnostics.Contracts; public class Dummy { public static void…
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
26
votes
2 answers

Contract.Requires throwing pex errors

Possible Duplicate: How Do You Configure Pex to Respect Code Contracts? Currently, when I run a pex exploration, the code contracts I created in my classes are being treated as errors in the pex exploration results. I thought when you ran pex…
Joshua Dale
  • 1,673
  • 3
  • 16
  • 25
26
votes
3 answers

How free can I be in the code in an object invariant?

I'm trying to demonstrate invariants in Code Contracts, and I thought I'd give an example of a sorted list of strings. It maintains an array internally, with spare space for additions etc - just like List, basically. When it needs to add an item,…
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
22
votes
2 answers

C# Code Contracts: What can be statically proven and what can't?

I might say I'm getting quite familiar with Code Contracts: I've read and understood most of the user manual and have been using them for quite a while now, but I still have questions. When I search SO for 'code contracts unproven' there are quite a…
JBSnorro
  • 4,274
  • 2
  • 25
  • 55
22
votes
1 answer

Question about [Pure] methods

Is the following method Pure? I'd say so, as it doesn't change in anyway the current class, thus, everything we can now currenly "see" in the class, before running this method will still be exactly the same after. Am I correct? class Set { ... …
devoured elysium
  • 90,453
  • 117
  • 313
  • 521
21
votes
2 answers

.Net Code Contracts - Where to learn more?

I had overheard some discussion in my office recently about .Net "Contracts" however, when I asked some of my fellow employees, not of them could easily explain to me what they were for, or what they even were. Does anyone have any resources,…
Paul Gleeson
  • 418
  • 4
  • 10
21
votes
2 answers

How to combine defensive programming techniques together?

The question I want to ask you is quite wide but in the same time it's very concrete. First, I have to say, that I mostly interested in answers which are applicable in the .net environment. Well, I want to increase the level of the code I produce.…
Igor Soloydenko
  • 7,161
  • 7
  • 39
  • 73
21
votes
5 answers

Comparing design by contract to type systems

I recently read a paper that compared Design-by-Contract to Test-Driven-Development. There seems to be lot of overlap, some redundancy, and a little bit of synergy between the DbC and TDD. For example, there are systems for automatically generating…
aleator
  • 4,346
  • 18
  • 31
21
votes
1 answer

Code Contracts [Type]implements interface method {Interface.Method} thus cannot add requires

I have the following scenario: public interface ISomething { void DoStuff(); //... } public class Something : ISomething { private readonly ISomethingElse _somethingElse; //... public Something (ISomethingElse somethingElse) …
roundcrisis
  • 16,035
  • 14
  • 55
  • 91
21
votes
3 answers

Can one make Code Analysis understand Code Contracts?

When using Code Analysis and Code Contracts in combination, I get a lot of warnings like CA1062: Microsoft.Design : In externally visible method 'Foo.Bar(Log)', validate parameter 'log' before using it. In Foo.Bar, I have a contract that validates…
1
2
3
43 44