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

后端 未结 4 1771
生来不讨喜
生来不讨喜 2021-02-03 20:01

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

4条回答
  •  鱼传尺愫
    2021-02-03 20:16

    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.

提交回复
热议问题