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

Code contracts and inheritance problems, what goes where?

I might be misunderstanding code contracts, but here's my situation. I have the following code: interface IFetch // defined in another DLL { T Fetch(int id); } interface IUserFetch : IFetch { IEnumerable GetUsersLoggedIn…
Bryan Boettcher
  • 4,412
  • 1
  • 28
  • 49
8
votes
2 answers

Why does CodeContracts warn me that "requires unproven: index < @this.Count" even though I have already checked the count?

I have code that looks something like this: public class Foo : ObservableCollection { private T bar; public Foo(IEnumerable items) : base(items.ToList()) { Contract.Requires(items != null); if…
Matthew
  • 28,056
  • 26
  • 104
  • 170
8
votes
2 answers

Code Contract understanding of error

I am just getting started with Code Contracts, and need a little help in correcting an error: Given this code: class MyClass { private bool _isUsed = false; public void SomeMethod() { Contract.Requires(!_isUsed); } } I get…
David Williams
  • 823
  • 6
  • 16
8
votes
1 answer

Contract preconditions in an empty-body constructor

Good morning! I'm writing a class for drawing histograms and, for user's convenience, I've decided to add a few convenience constructors. However, as soon as I recently switched to .NET code contracts from DevLabs, I want to make full use of…
wh1t3cat1k
  • 3,146
  • 6
  • 32
  • 38
8
votes
1 answer

How do I use code contracts in .NET 4.0 without making my code look cluttered?

I have started using Code Contracts and have found that it makes it difficult to immediately spot the 'guts' of a method. Take this (very simple) example: public static void UserAddNew(string domain, string username, string displayName) { …
8
votes
2 answers

Code Contracts - nice, on the edge, but not ready for prime time?

I got really captivated by code contracts introduced in .NET 4 (though with the help of DevLabs). But one fine print cooled me off quite a bit. Here is what it says: There is currently no workaround the problem when postconditions are called…
Schultz9999
  • 8,717
  • 8
  • 48
  • 87
8
votes
2 answers

How can i completely disable Code Contracts?

I currently have it setup like below. I had tried checking 'Perform Runtime Contract Checking' and then selecting 'None' but that seems unnecessary. If I have my project setup like below are code contracts completely disabled?
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
8
votes
3 answers

Does code contracts really help unit testing?

I have fair amount of knowledge on unit testing. I have been trying to read about code contracts. Does it really help unit testing? Is it over-rated especially when we talk about code-contract helping to do unit testing. I am specifically referring…
Sandbox
  • 7,910
  • 11
  • 53
  • 67
8
votes
3 answers

How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries?

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements. ie.…
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
8
votes
2 answers

Microsoft Code Contracts: Error "CodeContracts: Diagnostic: Failed to connect to any cache."

I get the following error when running Microsoft Code Contracts: CodeContracts: Diagnostic: Failed to connect to any cache.
Contango
  • 76,540
  • 58
  • 260
  • 305
8
votes
1 answer

"The type or namespace name '[Type]' is not valid in this scope" Error in visual studio Watch Window?

I was having trouble in Watch Window when I try to watch any type, I keep getting error "The type or namespace name '[Type]' is not valid in this scope". I had to give the full namespace along with the type in the watch window to fix this…
Carbine
  • 7,849
  • 4
  • 30
  • 54
8
votes
1 answer

Are code contracts guaranteed to be evaluated before chained constructors are called?

Before I started using Code Contracts I sometimes ran into fiddlyness relating to parameter validation when using constructor chaining. This is easiest to explain with a (contrived) example: class Test { public Test(int i) { if (i ==…
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
7
votes
1 answer

Code Contracts + Sandcastle -- Any way to customize the exceptions section?

I'm using Code Contracts ver: 1.4.40602.0 I copied the necessary Content and Transforms files Sandcastle outputs the exceptions based upon my contract requirements Example Code: public class MyClass { public MyClass(Object obj) { …
myermian
  • 31,823
  • 24
  • 123
  • 215
7
votes
5 answers

Code Contract, inheritance and Liskov Principle

I have in my code the concept of command : public abstract class BaseCommand { public BaseCommand() { this.CommandId = Guid.NewGuid(); this.State = CommandState.Ready; } public Guid CommandId { get; private set; } public CommandState…
Steve B
  • 36,818
  • 21
  • 101
  • 174
7
votes
1 answer

How to make code contracts work with deserialization of data contracts?

I have written a ContractInvariantMethod for a data contract class, and everything works great on the client side, however when an object of this type is sent to my service, and the Data Contract Deserializer tries to deserialize it, code contract…
Arash
  • 203
  • 1
  • 8