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

Code Contracts: invariants on super class of template method pattern not working?

Assume I have the following code: public abstract class TemplateBase { public void TemplateMethod() { Operation(); } protected abstract void Operation(); } public sealed class Implementation : TemplateBase { bool _alwaysTrue; …
Patrick Huizinga
  • 1,292
  • 9
  • 25
0
votes
0 answers

Code Contracts throws MethodAccess Exception when unit testing

I'm not quite sure why, but when I enable runtime contract checking, I'm getting a MethodAccessException during unit testing. I use the Machine.Specifications test framework and the ReSharper/dotCover test runner. When I test my assembly containing…
Tim Long
  • 13,000
  • 18
  • 75
  • 141
0
votes
1 answer

How are post-conditions implemented with CQRS?

How does CQRS handle post-conditions on immediately consistent models? I realise something like this is irrelevant on an eventually consistent system w/ event sourcing etc. But if I just wanted to apply vanilla CQRS to a simple interface, how would…
0
votes
2 answers

Code Contract to prevent duplicates on list

I'm currently checking with this contract that the parameter and the return value aren't null. Now, I need a way to check that no matter what branch of the switch it takes then the resulting IEnumerable must not have duplicates on its code values.…
Erre Efe
  • 14,878
  • 10
  • 41
  • 73
0
votes
1 answer

CodeContracts and null checks verbosity

I'm currently in the process of reducing some of the duplications I have in my application framework and I wonder what people think about the following extension method? [EditorBrowsable(EditorBrowsableState.Never)] public static class…
Eyal Alon
  • 1,846
  • 2
  • 25
  • 40
0
votes
2 answers

String assignment mystic issue. Variable name affects behavior

I have the following code inside a method: string username = (string)context["UserName"]; string un = (string)context["UserName"]; The problem is that the first string "username" is not assigned, while the second does. To make it more strange,…
aikixd
  • 506
  • 5
  • 15
0
votes
1 answer

Code Contracts - Static Checker doesn't get nullable types?

I think I found a bug in the static contract checking tool. Is there a way besides tagging the whole thing with [ContractVerification(false)] ? class Employee { public int? HierarchyLevel { get; private set; } public Employee(int? level) …
thomasch
  • 3
  • 1
  • 1
0
votes
1 answer

How can the code contracts compiler think this might be null?

I have hit multiple cases that seem to be a pattern: Contract.Ensures(Contract.Result() != null); ... BlahType Blah = new BlahType(); ... ... return Blah; and it gripes. In all cases the field is private and nothing else in the method…
Loren Pechtel
  • 8,549
  • 3
  • 27
  • 45
0
votes
1 answer

Preventing the use of certain dlls or service code in a given location

Is there a simple way (using code contracts perhaps?) to prevent the use of certainl dlls/namespace/assemblies within a given portion of an application? My use case is that I'd like a warning mechanism when I try to use a company wide service layer…
Jamie Dixon
  • 49,653
  • 18
  • 119
  • 157
0
votes
1 answer

How to prove to CodeContracts that the condition after a while loop is true

I'm trying to play with CodeContracts. I'm starting with a little function public static string MyTrim(string text) { Contract.Requires(text != null); Contract.Ensures(Contract.Result().Length == 0 || Contract.Result()[0] !=…
-1
votes
1 answer

CodeContracts on modulus (%) operator fail?

I'm writing a specialized randomizer class and want to ensure it's quality using CodeContracts. A typical randomizer method recieves an upper limit 'max' and returns a positive random value below that limit. public int Next(int max) { …
ILa
  • 49
  • 3
-1
votes
1 answer

The name does not exist in the current context in invariant method

I am trying to use invariants(code contracts library) in my program inside a carpark class where all my methods are implemented but "The name does not exist in the current context" appears.The highlighted words appeared to make the problem. The…
user11001389
-1
votes
1 answer

How to use DotNet.Contracts NuGet package?

Could someone shed some light on how to use the DotNet.Contracts NuGet package in Visual Studio 2015 and 2017? Is it the only component required to use Code Contracts in Visual Studio??? Do I still need to install Contracts.devlab9ts.msi??? When…
user2106007
  • 677
  • 1
  • 7
  • 10
-1
votes
1 answer

Code contracts static checks for reference types and null reference

Is that true that Code Contracts static analysis cannot check the explicit return new ... in a single branch methods (methods that don't have any conditionals and have only one return) like: static public Tuple Foo() { return new…
zerkms
  • 230,357
  • 57
  • 408
  • 498
-1
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,861
  • 5
  • 24
  • 44
1 2 3
43
44