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
5
votes
4 answers

CodeContracts - false positives

I've just started experimenting with CodeContracts in .NET 4 on an existing medium-sized project, and I'm surprised that the static checker is giving me compile-time warnings about the following piece of code: public class Foo { private readonly…
Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212
5
votes
1 answer

Code contracts, if X < Y and Y = Z+1 why is X < Z+1 not proved

I have a contract that does this: for (int i = 0; i < delegateParameterTypes.Length; i++) { Contract.Assert(i < delegateParameterTypes.Length); Contract.Assert(delegateParameterTypes.Length == methodParameters.Length + (1)); // Q.E.D. …
5
votes
2 answers

Autofac and Contract classes

Suppose we had the following: [ContractClass(typeof(ContractClassForIFoo))] public interface IFoo { int DoThing(string x); } public class Foo : IFoo { ... } [ContractClassFor(typeof(IFoo))] public class ContractClassForIFoo : IFoo { public…
user47589
5
votes
2 answers

What to do when using Contract.Assert(true) and the method must return something?

I have a bit of code with the following logic: //pseudo-code foreach (element in elementList) { if (element is whatever) return element; } } In theory, there is always one element that is whatever, so this method should pose no…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
5
votes
1 answer

Contract.Invariant not check by static verifier

I'm experimenting with Code Contract and I encountered one problem. I have class: public class SpecialPoint { public int X { get; set; } public int Y { get; set; } public SpecialPoint(int x, int y) { …
stachu
  • 277
  • 1
  • 3
  • 13
5
votes
4 answers

Method that does conditional return of method calling it?

Ok this might be a bit of hack but bear with me :) The background is that i'm tired of methods that that some if-statement to that messes up indention for the whole method, like: public SomeClass DoStuff(string inputStr) { SomeClass result…
Homde
  • 4,246
  • 4
  • 34
  • 50
5
votes
1 answer

Why do code contracts mark checks on generic type argument as unproven?

I defined a following example class having one generic method DoSomething: public static class MyClass { public static void DoSomething(T val) { System.Diagnostics.Contracts.Contract.Requires(typeof(T).IsEnum); } } And I have…
Edin
  • 1,476
  • 11
  • 21
5
votes
1 answer

Why would I want to use Code Contracts in public methods?

IMHO, since public methods with parameters can be called by any other programmer, it has the responsibility to verify parameter values and throw meaningful ArgumentException, should any of them be invalid. That being said, why would I prefer…
Crono
  • 10,211
  • 6
  • 43
  • 75
5
votes
0 answers

How to implement TryGetValue on a dictionary wrapper with code contracts

I'm implementing a class which implements IDictionary. But I'm not able to match the code contract for TryGetValue. Here's the relevant part of the code: class Wrapper : IDictionary { ... IDictionary
Michael Stoll
  • 1,334
  • 3
  • 13
  • 35
5
votes
1 answer

Code Contracts static checker seemingly unaware of Contract.Ensures of ReadOnlyCollection constructor

I recently installed Code Contracts Tools (Code Contracts for .NET) and Code Contracts Editor Extensions VS2012, and I'm having some trouble getting the static checker to work properly. When I run Code Contracts' static checker on the following code…
Sam
  • 291
  • 1
  • 5
5
votes
2 answers

CodeContracts "Required" understanding

I tried the following code to enable some kind of not null checking for retrieved entities to ensure they are exist before doing some concrete business: protected T GetRequired(object id) where T : EntityObject { var obj = Get(id); …
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
5
votes
3 answers

Enforcing the correct implementation of INotifyPropertyChanged with CodeContracts - "requires unproven"

I'm looking for an easy way to enforce the correct implementation of INotifyPropertyChanged i.e. when PropertyChanged is raised it must reference a property that is actually defined. I tried doing this with the new CodeContract tools from Microsoft,…
hwiechers
  • 14,583
  • 8
  • 53
  • 62
5
votes
1 answer

.NET code contracts: can it get more basic than this?

I was just messing around to answer someone's question here on Stack Overflow, when I noticed a static verification warning from inside my Visual Studio (2008): string[] source = { "1", "A", "B" }; var sourceObjects = Array.ConvertAll(source, c =>…
Thorarin
  • 47,289
  • 11
  • 75
  • 111
5
votes
2 answers

Where to Start with Code Contracts?

I saw an awesome demo of C# Code Contracts and I want to start implementing them into may code. I wish I had them in my code already. Where does one start? I failed to take away any printed materials from the demo. Any suggested reading? Any…
Rodney Hickman
  • 3,133
  • 11
  • 53
  • 83
4
votes
1 answer

Code Contracts chaining calls?

Basically I'm looking at 2 different situations: Method calls within the same class: public class MyClass { public Bar GetDefaultBar(Foo foo) { Contract.Requires(foo != null); return GetSpecificBar(foo, String.Empty); …
myermian
  • 31,823
  • 24
  • 123
  • 215