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

Contract.Requires for validations in web api

I am developing MVC5 / Web API based application. In some articles I have read use Contract.Requires (part of the System.Diagnostics.Contracts namespace) for validating the incoming data. Is this the correct way of validating the incoming data? Also…
Avinash Jain
  • 7,200
  • 2
  • 26
  • 40
4
votes
4 answers

Is there any reason not to use Run-time Contract Checking with Code Contracts?

I've recently listened to Kevin Hazzard talk about Code Contracts in .Net Rocks show 570 (http://devjourney.com/community/dotnet-rocks-show-570-with-kevin-hazzard/). He mentions enabling Run-time Contract Checking as an option some people might…
urig
  • 16,016
  • 26
  • 115
  • 184
4
votes
1 answer

Is there an alternative to Code Contracts for declaring coding assumptions?

I use Code Contracts. I like Code Contracts. Code Contracts for C#, however, are far from perfect. Most of the issues related to them I have been able to maneuver around or soften with policies. Still... there are a few parts of it that make me…
Bill Nadeau
  • 702
  • 1
  • 9
  • 15
4
votes
2 answers

Code contracts usage patterns when dealing with Files

I've just started using Code Contracts with .NET and I had a guard clause like this if (!file.Exists(path)) throw FileNotFoundException(); and replaced it with Contract.Requires(File.Exists(path)); I'm not sure this is correct, because the…
roundcrisis
  • 17,276
  • 14
  • 60
  • 92
4
votes
1 answer

How to prove to CodeContracts that IEnumerable.Single() never returns null?

I have the following code snippet: public static string returnString() { string[] stringList = { "a" }; if (stringList.Count() != 1) { throw new Exception("Multiple values in list"); } …
Rufus Buschart
  • 362
  • 1
  • 13
4
votes
1 answer

Which 3rd party Code-by-Contract library is most like MS's .NET 4.0 library?

I want to jump into coding by contract. I got VS2010 (with the C# 4.0 compiler) but I have to target the 3.5 framework. What 3rd party code by contract library has classes and interface the most like the .NET 4.0 ones?
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
4
votes
2 answers

For reliable code, NModel, Spec Explorer, F# or other?

I've got a business app in C#, with unit tests. Can I increase the reliability and cut down on my testing time and expense by using NModel or Spec Explorer? Alternately, if I were to rewrite it in F# (or even Haskell), what kinds (if any) of…
ja.
  • 4,245
  • 20
  • 22
4
votes
2 answers

How do I imply code contracts of chained methods to avoid superfluous checks while chaining?

I'm using Code Contracts in C# 4.0. I'm applying the usual static method chaining to simulate optional parameters (I know C# 4.0 supports optional parameters but I really don't want to use them). The thing is that my contract requirements are…
Sandor Drieënhuizen
  • 6,310
  • 5
  • 37
  • 80
4
votes
1 answer

Code Contracts with no dlls on disk on asp.net 5/vnext

Asp.Net vnext/5 uses roslyn for on-the-fly compilation, not producing any assemblies at all. Most code contract tools use compile-time code transformations to translate contracts to runtime checks. How is it going to work with Asp.Net 5? I love…
Lev
  • 434
  • 2
  • 9
4
votes
2 answers

IOC Container Handling State Params in Non-Default Constructor

For the purpose of this discussion, there are two kinds of parameters an object constructor might take: state dependency or service dependency. Supplying a service dependency with an IOC container is easy: DI takes over. But in contrast, state…
4
votes
1 answer

Differences between Code Contract and Spec#

I want to implement the DBC in C#. I faced with the Spec# and Code Contract for it. What is the difference between Spec# and Code Contract?
tvahid
  • 210
  • 1
  • 9
4
votes
3 answers

Books on Code Contracts in C# 4.0

Altough I've known Code Contracts for some time, as I've used it a bit in Java, I would like to start using them in C#, now that they are part of C# 4.0. I am looking on learning material, books or vids. Altough tutorials are also welcome, I'd like…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
4
votes
1 answer

F# argument checking

F# has some nice succint argument checking functions that can be used like this: let foo (bar : string) : string = if bar = null then nullArg "bar" ... I prefer a more prescriptive expression, however, a la Code Contracts: let foo…
Bent Rasmussen
  • 5,538
  • 9
  • 44
  • 63
4
votes
3 answers

Code Contracts and ASP.NET MVC Controller properties

I am using CodeContracts for the first time, and I have a question regarding it. When I use ModelState, User, Request or Response in my controller code then Code Contracts is saying that I should add a Contract.Requires(this.Request != null) to my…
SynerCoder
  • 12,493
  • 4
  • 47
  • 78
4
votes
2 answers

Code Contract's properties in Visual Studio 2010 Pro RC

So it seems there should be a "Code Contracts" tab in Visual Studio 2010's properties. I can't find it anywhere. Maybe it's a problem with my Visual Studio installation? I am running the RC version. This is what I have: alt text…
devoured elysium
  • 101,373
  • 131
  • 340
  • 557