Search code examples
visual-studio-2017aoppostsharpcode-contractsdesign-by-contract

Code Contracts is not supported in Visual Studio 2017, How to implement it with PostSharp?


At the time of writing this question CodeContracts by Microsoft, the Visual Studio extension that implements Design by Contract for .NET is not supported in Visual Studio 2017.

Looking at the insights of this project in GitHub here it seems that this project is dead. In the last years, the support for this extension has been always being delayed for all the visual studio releases. In my opinion, it would be dangerous to insist using Microsoft´s Code Contracts for new projects because of the lack of interest and support.

How would you implement Design by Contract using Postsharp's Aspect Oriented Programming Framework using IL Code Weaving? How would look the implementations of the Class Invariants? The validity of the Class Invariants has to be checked at the beginning and at the end of all public methods that interact with the class in question.


Solution

  • PostSharp offers code contracts applicable on method parameters, fields and properties. These are documented at http://doc.postsharp.net/contracts.

    Class invariants (as described at https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts#invariants) are not provided out of the box.