Code Contracts
suggest changeVersions
C# 4.0 and later.
Syntax
- Contract.Requires(Condition,userMessage)
Contract.Requires<T>(Condition,userMessage)
Contract.Result<T>
Contract.Ensures()
Contract.Invariant()
Remarks
.NET supports Design by Contract through the Contract class in the System.Diagnostics.Contracts namespace, introduced in .NET 4.0. The Code Contracts API includes static and runtime checks and lets you define preconditions, postconditions, and invariants for a method. Preconditions specify what the parameters must fulfill before a method can execute, postconditions are verified when the method completes, and invariants define conditions that do not change during execution of a method.
Why are Code Contracts needed?
Tracking issues while an application is running is one of the foremost concerns of developers and administrators. Tracking can be performed in many ways. For example:
- You can apply tracing to your application and get details while 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 returned from a method call, preconditions, postconditions, and invariants ensure that everything entering and leaving your methods is correct.