Home > Articles > Programming > Windows Programming

Code Contracts in .NET 4.0

  • Print
  • + Share This
Code contracts in .NET 4 provide a language-agnostic way to describe the contract of a method or class using pre-conditions, post-conditions, and invariants. .NET expert Scott Dorman shows how code contracts, when used in combination with the code contracts tools, can be used to improve testing through runtime checking, perform static contract verification, and produce documentation based on expanded XML documentation comments.
Like this article? We recommend

As an application executes, it can encounter any number of possible error conditions. The .NET Framework provides a very rich set of exceptions for runtime errors that encapsulate all of the information about an error in a single class. While it is possible to write applications that are robust and minimize the possibility of a runtime exception occurring, it isn't always an easy task.

Whenever you write code, the implementation contains a set of assumptions about the inputs and outputs. Sometimes these assumptions are defined by the business logic being implemented, in which case they may be explicitly defined. However, they can also be implied assumptions, in which case they aren't documented at all. No matter whether they are explicit or implied, those assumptions still exist but they may not be clearly stated (if they are stated at all) in the actual source code you are writing.

Commenting Your Code

One of the simplest ways to document those assumptions is to comment your code. Good comments make it easier to understand what the code is doing and, more importantly, why it is doing it a particular way. Comments are meant to be read by programmers and should be clear and precise. A comment that is hard to understand or incorrect isn't much better than having had no comment at all.

Adding clear and precise comments to your code means that you don’t have to rely on memory to understand the “what” and “why” of a section of code. This is most important when you look at that code later on, or someone else must look at your code. Because comments become part of the textual content of your code, they should follow good writing principles in addition to being clearly written.

To write a good comment, you should do your best to document the purpose of the code (the “why,” not “how”), and indicate the reasoning and logic behind the code as clearly as possible. Ideally, comments should be written at the same time as you write the code. If you wait, you probably won’t go back and add them.

  • + Share This
  • 🔖 Save To Your Account