user1935724
user1935724

Reputation: 554

Issues with Contract.Requires() and loop invariant

I am following the codecontracts tutorial (https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts#usage-guidelines) and I seem to have trouble getting the simplest thing working. Given the method definition

public int Add(int x, int y)
{
   Contract.Requires(x > 0);
   Contract.Requires(y > 0);

   return x+y;
}

when I am calling o.Add(0,0) The method does not fail the pre-condition check. When I am in debugging mode, the Contract.Requires() statements are skipped. Where I am doing wrong?

Second question can I use Contract.Invariant() to check loop invariant? According to the definition of object invariant Object invariants are conditions that should be true for each instance of a class whenever that object is visible to a client.which seems to be a little different from loop invariant since in each loop iteration the loop invariant may not be necessarily visible to a client so it may violates the property but not get checked. Is this understanding correct?

Upvotes: 0

Views: 59

Answers (1)

Ɖiamond ǤeezeƦ
Ɖiamond ǤeezeƦ

Reputation: 3331

In answer to your first question, download and run the Code Contracts .msi file from here. The .msi file includes the static checker and the binary rewriter (for runtime checking), which modifies a program by injecting the contracts causing them to be checked as part of program execution. Without the rewriter, contracts will not be checked. Please note that the rewritter only works with Visual Studio 2013 and 2015.

In answer to your second question, you cannot use Contract.Invariant() to check a loop invariant. I would suggest using Contract.Assume() within the loop.

Upvotes: 0

Related Questions