C# Futures: Method Contracts

For several years, developers have had the ability to add method level contracts via the Code Contracts research project. But this has a number of problems. It uses an imperative syntax that is verbose and poorly supported by tooling. To actually use the contract, both in the library and application, a post-compiler needs to be run. All in all it is an interesting project, but it needs first class compiler and syntax support to be useful.

Proposal 119, Method Contracts, seeks to offer this support. Like generic constraints, the pre- and post-conditions would be listed between the method signature and the body.

There are three new keywords under this proposal. The phrase beginning with “requires” deals with pre-conditions. This is mostly going to be used for checking parameters, but in theory could also look at the state of the object itself. The keyword “ensures” is used for setting up post conditions. It would reuse the “return” keyword to refer to the result of the method call.