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
0
votes
1 answer

How does the exception instance gets created within code contracts

For example, consider the following code snippet Contract.Requires(arg !=null) during the runtime, the following code will throw the exception of type CustomException. Does code contract use Activator to create an instance of the…
Saran
  • 99
  • 2
  • 14
0
votes
2 answers

PostSharp code contract for GreaterThan does not fire when the values are equal

when using postsharp code contracts I have set a GreaterThan attribute to 0. I have an action with an id decorated with the GreaterThan contract public virtual ActionResult Edit([GreaterThan(0)] int id) when I call the…
eiu165
  • 6,101
  • 10
  • 41
  • 59
0
votes
2 answers

Better (legible) way to perform runtime check without adding boilerplate?

I have this piece of code that consumes too much vertical space and it's too verbose. if (property == null) { throw new XamlParseException($"Cannot find a property named \"{Name}\" in the type {underlyingType}"); } Isn't there…
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
0
votes
0 answers

Code Contract : ccrewrite exited with code -1073741571

I use code contracts and local build with VS 2013 is fine, but on build server i get the next error: MSB3073: C:\Program Files (x86)\Microsoft\Contracts\MsBuild\v14.0\Microsoft.CodeContracts.targets(642,5): The command ""C:\Program Files…
gsv
  • 277
  • 1
  • 9
0
votes
1 answer

C# Code Contracts: Array operations

For university I must learn how to deal with Code Contracts in C#. I want to use it for this method which should return the smallest Element in the Array: public int minarray(int[] minarray) Here is what I got but I have no idea whether this is…
今天春天
  • 941
  • 1
  • 13
  • 27
0
votes
0 answers

Extract method with contract

In a powerpoint slideshow I saw about code contracts they right click on some code and get the option to "extract method with contract". But I dont get that option? How is it possible to extract a method with contract? Regards
0
votes
1 answer

CodeContracts for specific generic interface

I would like to use CodeContracts for validating some specific implementations of generic interface. I had a basic generic interface public interface IEnityMap { TDest Map(TSource); } I want to determine CodeContracts for…
0
votes
1 answer

How do I tell in c# codecontracts that a external method never returns null?

I have the following piece of c# code: myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value; CodeContract knows that myClaimsIdentity is never null. But it complains that the FindFirst(string) method might return null: Warning …
Rufus Buschart
  • 362
  • 1
  • 13
0
votes
1 answer

Check if object have attribute with codecontracts

I have method in factory class internal Window GetWindow(int siteId) { Contract.Requires(siteId > 0); Window result; //some logic that create specific window return result; } Lets assume i have…
nuclear sweet
  • 1,079
  • 10
  • 27
0
votes
1 answer

Using Contracts in C# reduce the number of unit tests

It’s true that using Contracts.Requires and Contracts.Ensure in C# methods will reduce the necessary unit tests for that methods? Can I just ignore the range of values that are not in conformity with the contracts or those values should also be…
miguelbgouveia
  • 2,963
  • 6
  • 29
  • 48
0
votes
2 answers

In C# should I use uint or int for values that are never supposed to be negative?

Possible Duplicate: Should I use uint in C# for values that can’t be negative? Suppose that the MaxValue of (roughly :) ) 2^31 vs 2^32 does not matter. On one hand, using uint seems nice because it is self-explanatory, it indicates (and…
Hamish Grubijan
  • 10,562
  • 23
  • 99
  • 147
0
votes
3 answers

CodeContracts: Array access might be above the upper bound

I'm getting these warnings from CodeContracts: Array access might be above the upper bound. Did you meant 0 instead of 1? Array access might be above the upper bound. Did you meant 1 instead of 2? Array access might be above the upper bound.…
user47589
0
votes
2 answers

Using Code Contracts in unit tests

Do you think it is advisable to use Code Contracts inside your unit tests? I don't think it is since it is like creating unit tests to test your unit tests. Therefore I would not activate the Code Contracts Static Checking nor the Runtime Checking…
Luca Cremonesi
  • 144
  • 2
  • 3
  • 13
0
votes
3 answers

"Contract section within try block" error for context connection

I have written this snippet and its contract: [Pure] public string getLevelName() { using (var c = new myContext()) { Contract.Ensures(Contract.Result() == c.Level.FirstOrDefault(i => i.levelId == this.levelId).name); …
Majid
  • 13,853
  • 15
  • 77
  • 113
0
votes
2 answers

Code Contracts: ensure constraint on delegate to avoid "requires unproven" warning?

I have a class which allows a switch-like statement using any object type T and allows specifying a return type R. When I try to require non-null values I receive a warning that it requires unproven: value != null. Figured an Assume would take away…
Stefan de Kok
  • 2,018
  • 2
  • 15
  • 19