.NET supports the Design by Contract idea via its Contracts class found in the System.Diagnostics namespace and introduced in .NET 4.0. Code Contracts API includes classes for static and runtime checks of code and allows you to define preconditions, postconditions, and invariants within a method. The preconditions specify the conditions the parameters must fulfill before a method can execute, postconditions that are verified upon completion of a method, and the invariants define the conditions that do not change during the execution of a method.
Why are Code Contracts needed?
Tracking issues of an application when your application is running, is one the foremost concerns of all the developers and administrators. Tracking can be performed in many ways. For example -
You can apply tracing on our application and get the details of an application when the application is running
You can use event logging mechanism when you are running the application. The messages can be seen using Event Viewer
You can apply Performance Monitoring after a specific time interval and write live data from your application.
Code Contracts uses a different approach for tracking and managing issues within an application. Instead of validating everything that is returned from a method call, Code Contracts with the help of preconditions, postconditions, and invariants on methods, ensure that everything entering and leaving your methods are correct.
Defining Contracts on Interface
In the above code, we have defined an interface called IValidation with an attribute [ContractClass]. This attribute takes an address of a class where we have implemented a contract for an Interface. The class ValidationContract makes use of properties defined in the interface and checks for the null values using Contract.Requires<T>. T is an exception class.
We have also marked the get accessor with an attribute [Pure]. The pure attribute ensures that the method or a property does not change the instance state of a class in which IValidation interface is implemented.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0