Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a practical usage of Code Contracts in .NET 4.0?

In order to fully understand and take advantage of the new features and enhancements provided with the coming of the new .NET Framework 4.0, I would like to get an example of real-world application of Code Contracts.

  1. Anyone has a good example of application of this feature?

I would like to get a code sample with a brief explanation to help me get up and running with it.

like image 566
Will Marcouiller Avatar asked May 27 '10 17:05

Will Marcouiller


People also ask

Which of the following are benefits of code contracts in .NET framework?

Improved testing: Code contracts provide static contract verification, runtime checking, and documentation generation. Automatic testing tools: You can use code contracts to generate more meaningful unit tests by filtering out meaningless test arguments that do not satisfy preconditions.

What is the design by contract feature in the .NET framework?

Microsoft has released a library for design by contract in version 4.0 of the . net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code.

What is net contracts?

Net contract price is the total U.S. dollar amount of the Supply Contract less the total dollar amount of Excluded Goods and Services less the dollar amount of Local Costs.


1 Answers

From The Code Contracts User Manual:

Contracts allow you to express preconditions, postconditions and object invariants in your code for runtime checking, static analysis, and documentation.

Code Contracts are used for static verification; imagine if - at compile time - you caught not only syntax errors but also logic errors. This is the vision of static program verification.

Real World Example

You could use contracts (and static verification) to reduce the cost of testing... in particular regression testing. As an example, let's say I write some code which fulfills some business needs... but later, performance needs change, and I'm required to optimize. If I first write a contract, then - when my new optimized code is verified - if it no longer fulfills the original contract I'll get an error message in my IDE, just like if I had a compile time error. As a result, you find and resolve the bug almost immediately, which costs less than a round of testing.

like image 96
Richard JP Le Guen Avatar answered Oct 09 '22 00:10

Richard JP Le Guen